In the following example, a mutex is used to protect a file:
#include <fstream>
#include <memory>
#include <mutex>
std::mutex m;
int main() {
std::unique_ptr<std::lock_guard<std::mutex>> ptr_1 = std::make_unique<std::lock_guard<std::mutex>>(m);
std::fstream file_1("file_name.txt");
std::unique_ptr<std::lock_guard<std::mutex>> ptr_2{std::move(ptr_1)};
}
When the destructors are called, the mutex will be unlocked before the file is closed. This can cause a race condition. It seems to me that there must be some guideline about move-operations, destructors, or ownership that I don't know about. What design guideline has been broken?