当C++ 11我已经创建了下面的例子测试线程:的std ::线程类的构造函数和析构函数
#include <iostream>
#include <thread>
class Foo {
public:
Foo(void) {
std::cout << "Constructor called: " << this << std::endl;
}
~Foo(void) {
std::cout << "Destructor called: " << this << std::endl;
}
void operator()() const {
std::cout << "Operatior called: " << this << std::endl;
}
};
void test_normal(void) {
std::cout << "====> Standard example:" << std::endl;
Foo f;
}
void test_thread(void) {
std::cout << "====> Thread example:" << std::endl;
Foo f;
std::thread t(f);
t.detach();
}
int main(int argc, char **argv)
{
test_normal();
test_thread();
for(;;);
}
打印出以下几点:
为什么析构函数调用了6次线程?为什么线程报告不同的内存位置?
编辑 当添加移动和复制构造函数输出:
我明白了。我现在把我的输出添加到了帖子中。看起来我有3个额外的移动构造函数调用。这与编译器有关吗? – toeplitz
会有当你创建'Foo'一个对象调用构造,当您将它传递给线程构造一个拷贝构造调用。其余的与实施有关。 – Praetorian