Search code examples
c++wikipediaraii

RAII Example from Wikipedia


I was looking at the C++ example of RAII on wikipedia, and I came across something that didn't make sense to me.

Here's the code snippet itself, all credit to 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)
}

That comment at the end says: "file will be closed first... mutex will be unlocked second...". I understand the concept of RAII, and I get what the code is doing. However, I don't see what (if anything) guarantees the order which that comment claims.

To end with a question mark: what guarantees that the file is closed before the mutex is unlocked?


Solution

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

    Because this is how C++ is designed: scoped objects (whatever the scope is: class, function, local block, ...) are destroyed in the reverse order in which they are initialized. There is really nothing more to say, it's just part of the spec.