问题
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