我正在尝试确定以下代码是否安全,或者它是否是 UB 并且恰好在这种情况下运行良好(运行 here ):
#include <iostream>
#include <mutex>
struct Foo
{
std::mutex mutex;
~Foo()
{
std::lock_guard<std::mutex> lock(mutex);
}
};
int main()
{
{
Foo foo;
}
std::cout << "everything seems to work fine...?" << std::endl;
}
具体来说,我们能否保证在析构函数内部定义的局部变量在成员变量之前被析构?
我从 cppreference.com 中找到了以下内容,但它似乎并没有完全回答我的问题:
Destruction sequence
For both user-defined or implicitly-defined destructors, after the body of the destructor is executed, the compiler calls the destructors for all non-static non-variant members of the class, in reverse order of declaration, then it calls the destructors of all direct non-virtual base classes in reverse order of construction (which in turn call the destructors of their members and their base classes, etc), and then, if this object is of most-derived class, it calls the destructors of all virtual bases.
最佳答案
根据[class.dtor]/9中的标准,
After executing the body of the destructor and destroying any automatic objects allocated within the body, a destructor for class
X
calls the destructors forX
’s direct non-variant non-static data members, the destructors forX
’s non-virtual direct base classes and, ifX
is the type of the most derived class (15.6.2), its destructor calls the destructors forX
’s virtual base classes. ...
这肯定地回答了您的问题。
关于c++ - 在析构函数中持有 std::lock_guard 是否安全?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55942966/