gpt4 book ai didi

c++ - 当 C++ 中需要自动删除时,这种静态用法是否正确?

转载 作者:行者123 更新时间:2023-12-01 14:35:48 25 4
gpt4 key购买 nike

code snippet来自维基百科。

void WriteToFile(const std::string& message) {
// |mutex| is to protect access to |file| (which is shared across threads).
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 first when leaving scope (regardless of exception)
// mutex will be unlocked second (from lock destructor) when leaving scope
// (regardless of exception).
}

此片段用于演示 RAII。当离开 WriteToFile 范围时,互斥量将被解锁。我的问题是,由于 mutex 被声明为 static,它应该存在直到整个程序退出,对吗?那么为什么在离开作用域时会调用互斥析构函数呢?我认为互斥析构函数只在主程序退出后调用一次,正如 C++ 标准所指定的那样。

有人给我解释一下吗?

最佳答案

it should exist until the whole program exit, right?

是的


So why would the mutex destructor be called when leaving the scope?

互斥析构函数不会被调用。锁守卫析构函数将被调用,它将解锁互斥量。

来自 cppreference

When a lock_guard object is created, it attempts to take ownership ofthe mutex it is given. When control leaves the scope in which thelock_guard object was created, the lock_guard is destructed and themutex is released.


I think the mutex destructor only be called once after the mainprogram exit

是的

关于c++ - 当 C++ 中需要自动删除时,这种静态用法是否正确?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62772590/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com