c++ - 来自维基百科的 RAII 示例

标签 c++ wikipedia raii

我在看 the C++ example of RAII on wikipedia ,我遇到了一些对我来说没有意义的事情。

这是代码片段本身,全部归功于维基百科:

#include <string>
#include <mutex>
#include <iostream>
#include <fstream>
#include <stdexcept>

void write_to_file (const std::string & message) {
    // mutex to protect file access
    static std::mutex mutex;

    // lock mutex before accessing file
    std::lock_guard<std::mutex> lock(mutex);

    // try to open file
    std::ofstream file("example.txt");
    if (!file.is_open())
        throw std::runtime_error("unable to open file");

    // write message to file
    file << message << std::endl;

    // file will be closed 1st when leaving scope (regardless of exception)
    // mutex will be unlocked 2nd (from lock destructor) when leaving
    //     scope (regardless of exception)
}

末尾的评论说:“文件将首先关闭……互斥体将第二个被解锁……”。我了解 RAII 的概念,也了解代码的作用。但是,我看不出有什么(如果有的话)保证该评论所声称的顺序。

以问号结尾:什么保证文件在互斥锁解锁之前关闭?

最佳答案

what guarantees that the file is closed before the mutex is unlocked?

因为这就是 C++ 的设计方式:作用域对象(无论作用域是什么:类、函数、本地 block ...)按照与初始化相反的顺序销毁。真的没什么可说的,它只是规范的一部分。

关于c++ - 来自维基百科的 RAII 示例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16243174/

相关文章:

c++ - 返回指向结构的指针,如何自动释放内存?

c++ - C/C++ 后递增/递减和函数调用

c++ - 将 Visual C++ 代码转换为 Borland C++Builder

r - 如何保存大型数据框并在 R 中快速加载它?

c++ - CComPtr 和 RAII

C++ 优化器删除具有副作用的对象

c++ - 迭代多个序列。 C++11 中的容器

c++ - ISO/IEC 10646 中的 "character short name"是什么?

mysql - 如何仅查找 Wikipedia 信息框数据并将其导入 MySQL 数据库?

mysql - 像维基百科一样在 div 中创建 div