我在看 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/