2

在 wikipedia 上查看 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)
}

最后的评论说:“文件将首先关闭......互斥锁将被解锁......”。我了解 RAII 的概念,并且知道代码在做什么。但是,我看不出是什么(如果有的话)保证了该评论声称的顺序。

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

4

2 回答 2

6

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

因为这就是 C++ 的设计方式:作用域对象(无论作用域是什么:类、函数、本地块……)以它们初始化的相反顺序被销毁。真的没什么好说的了,这只是规范的一部分。

于 2013-04-26T18:44:11.860 回答
1

其背后的原因是函数的调用堆栈是如何工作的。调用堆栈是存储函数局部变量的内存部分(除了其他东西)。调用堆栈就像一堆盘子一样工作。函数中的每个新变量都会在其堆中添加一个盘子。在函数结束时,所有板都从堆中移除,从顶部开始。这是创建的相反顺序。

有关调用堆栈的更多信息,您可以在此处查看:http: //www.learncpp.com/cpp-tutorial/79-the-stack-and-the-heap/

于 2013-07-18T10:39:37.683 回答