在按功能对象构造线程时多次调用复制构造函数

时间:2018-04-07 04:41:03

标签: c++ multithreading copy-constructor function-object

我尝试将一个函数对象传递给一个线程。当我发现复制构造函数在'main'线程中被调用两次时,我很困惑。为什么不简单地复制一次而不是两次?第二个副本没用。

代码段:

#include <iostream>
#include <thread>
using namespace std;

struct A
{
    A()
    {
        cout << "constructor      this=" << this << " thread_id=" << this_thread::get_id() << endl;
    }
    A(const A &other)
    {
        cout << "Copy constructor this=" << this << " thread_id=" << this_thread::get_id() << endl;
    }
    void operator()()
    {
        cout << "operator()       this=" << this << " thread_id=" << this_thread::get_id() << endl;
    }
    ~A()
    {
        cout << "destructor       this=" << this << " thread_id=" << this_thread::get_id() << endl;
    }
};

int main()
{
    A a;
    thread t(a);
    t.join();
    return 0;
}

结果如下:

constructor      this=0x7ffee91f5888 thread_id=0x7fff8b2a6340
Copy constructor this=0x7ffee91f5370 thread_id=0x7fff8b2a6340
Copy constructor this=0x7fb8de402870 thread_id=0x7fff8b2a6340
destructor       this=0x7ffee91f5370 thread_id=0x7fff8b2a6340
operator()       this=0x7fb8de402870 thread_id=0x700007c95000
destructor       this=0x7fb8de402870 thread_id=0x700007c95000
destructor       this=0x7ffee91f5888 thread_id=0x7fff8b2a6340

0 个答案:

没有答案