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

标签 c++ multithreading destructor

我正在尝试确定以下代码是否安全,或者它是否是 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/

相关文章:

c++ - 为什么我不能使用两个scanf函数来输入字母

C++ - 通过模板类进行模板特化

C++ 跳过调用中的第一个默认参数

c++ - 传递给 std::variant 的预定义类型列表

wpf - 如何从Task更新CollectionViewSource的Source属性?

java - 两个同步方法是否同时执行

multithreading - 如何在Flutter中显示带有后台任务的AlertDialog

c++ - 调用结构默认析构函数?

java - 如何清理 Java 中打开的进程?

c++ - 在一个类的析构函数中应该删除的所有内容