【问题标题】:c++ std::thread calling method from object cause to calling destructor of this classc++ std::thread从对象原因调用方法调用这个类的析构函数
【发布时间】:2020-02-03 17:13:10
【问题描述】:

我对这段代码有几个问题:

#include <thread>
#include <unistd.h>
#include <iostream>

class A
{
public:
    ~A()
    {
        std::cout << "Destructor A: " << this << std::endl;
    }

    void operator()()
    {
        std::cout << "going to sleep 10 seconds.." << std::endl;
        sleep(10);
        std::cout << "wake" << std::endl;
    }
};

int main()
{
    std::cout << "begin" << std::endl;
    A* a = new A();
    std::thread th(*a);
    th.join();
    std::cout << "end" << std::endl;
    delete a;

    return 0;
}

输出:

g++ -std=c++17 test.cpp -pthread
./a.out 
begin
Destructor A: 0x7fff0b6bed27
going to sleep 10 seconds..
wake
Destructor A: 0x559d4e8012a8
end
Destructor A: 0x559d4e801280
  1. 为什么在调用 std::thread th(*a) 之后我实际上得到了一个析构函数调用?这没有意义。
  2. 为什么从不同的实例对同一个析构函数有 3 次调用?在我的代码中,我创建了 A 的 1 个实例,并在 main 函数的末尾将其删除。所以它应该只是 A destrutor 的 1 个打印件。
  3. 在调用 std::thread th(*a) 时,std::thread 的构造函数是使用 'a' 作为引用还是创建它的新实例(通过调用 A 的复制构造函数)?

谢谢。

【问题讨论】:

    标签: c++ linux multithreading destructor


    【解决方案1】:
    1. 由于std::thread 无法确定您传递给它的值在创建线程后是否存在,它会复制您传递的值。

    2. decay_copy 完成的另一个副本,在 std::thread 的构造函数中调用。

    3. 新实例。

    std::thread的构造函数可以在这里详细解释:https://en.cppreference.com/w/cpp/thread/thread/thread

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-04-16
      • 2012-06-15
      • 1970-01-01
      • 2021-08-03
      • 1970-01-01
      • 1970-01-01
      • 2014-10-23
      相关资源
      最近更新 更多