【发布时间】: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
- 为什么在调用 std::thread th(*a) 之后我实际上得到了一个析构函数调用?这没有意义。
- 为什么从不同的实例对同一个析构函数有 3 次调用?在我的代码中,我创建了 A 的 1 个实例,并在 main 函数的末尾将其删除。所以它应该只是 A destrutor 的 1 个打印件。
- 在调用 std::thread th(*a) 时,std::thread 的构造函数是使用 'a' 作为引用还是创建它的新实例(通过调用 A 的复制构造函数)?
谢谢。
【问题讨论】:
标签: c++ linux multithreading destructor