ウィキペディアで 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)
}
最後のコメントには、「ファイルは最初に閉じられます...ミューテックスは2番目にロック解除されます...」と書かれています。RAII の概念を理解し、コードが何をしているかを理解しています。ただし、そのコメントが主張する順序を保証するもの (もしあれば) はわかりません。
疑問符で締めくくります: ミューテックスのロックが解除される前にファイルが閉じられることを保証するものは何ですか?