std :: thread,类构造函数和析构函数

toe*_*itz 2 c++ multithreading c++11 stdthread

在C++ 11中测试线程时,我创建了以下示例:

#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(;;);
}
Run Code Online (Sandbox Code Playgroud)

其中打印以下内容:

在此输入图像描述

为什么析构函数被调用了6次?为什么线程会报告不同的内存位置?

编辑 添加移动和复制构造函数输出时:

在此输入图像描述

Die*_*ühl 6

将移动或复制功能对象.您没有在输出中考虑任何这些.