【发布时间】:2013-04-26 18:42:19
【问题描述】:
我在查看the C++ example of RAII on wikipedia,发现了一些对我来说没有意义的东西。
这是代码 sn-p 本身,全部归功于维基百科:
#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 的概念,并且知道代码在做什么。但是,我看不出是什么(如果有的话)保证了该评论声称的顺序。
以问号结尾:什么保证文件在互斥锁解锁之前关闭?
【问题讨论】:
-
维基百科在该代码下方立即回答了您的问题:“局部变量允许在单个函数中轻松管理多个资源:它们以构造的相反顺序被销毁,并且对象仅如果完全构造,则销毁——也就是说,如果没有异常从其构造函数传播。"
-
@Pubby:好吧,你看一下。我想我只是完全错过了我的眼睛。对不起。