Copy constructor is called many times when constructing a thread by function object

旧街凉风 提交于 2019-12-04 13:38:19

问题


I try to pass a function object to a thread. I am confused when I found the copy constructor is called two times in the 'main' thread. Why not simply copy once instead of twice? The second copy is useless.

Code Snippet:

#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;
}

The result is below:

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

来源:https://stackoverflow.com/questions/49703908/copy-constructor-is-called-many-times-when-constructing-a-thread-by-function-obj

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!