来自维基百科的RAII示例

Sha*_*ley 2 c++ wikipedia raii

在维基百科上看到了RAII的C++示例,我遇到了一些对我没有意义的事情.

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

#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)
}
Run Code Online (Sandbox Code Playgroud)

最后的评论说:"文件将首先关闭......互斥锁将被解锁第二......".我理解RAII的概念,我得到了代码正在做的事情.但是,我没有看到(如果有的话)保证该评论所声称的顺序.

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

sya*_*yam 6

什么保证在互斥锁解锁之前文件已关闭?

因为这就是C++的设计方式:范围对象(无论范围是什么:类,函数,本地块,...)都按照它们初始化的相反顺序销毁.实际上没有什么可说的了,它只是规范的一部分.