Frage

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?

War es hilfreich?

Lösung

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.

Andere Tipps

The reason behind it is how the call stack of a function works. The call stack is the part of memory where the function local variables are stored (besides other things). The call stack works like a pile of plates. Each new variable inside a function adds a plate to its pile. At the end of a function all the plates are removed from the pile, starting at the top. Which is the reverse order of creation.

For more information about the call stack you can look here: http://www.learncpp.com/cpp-tutorial/79-the-stack-and-the-heap/

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top