gpt4 book ai didi

c++ - 在析构函数中持有 std::lock_guard 是否安全?

转载 作者:塔克拉玛干 更新时间:2023-11-03 00:09:26 37 4
gpt4 key购买 nike

我正在尝试确定以下代码是否安全,或者它是否是 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 for X’s direct non-variant non-static data members, the destructors for X’s non-virtual direct base classes and, if X is the type of the most derived class (15.6.2), its destructor calls the destructors for X’s virtual base classes. ...

这肯定地回答了您的问题。

关于c++ - 在析构函数中持有 std::lock_guard 是否安全?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55942966/

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