为什么在下面的示例代码中,对象被复制了两次?根据线程类的文档构造函数将所有参数复制到线程本地存储,因此我们有理由进行第一次复制。第二个呢?
class A {
public:
A() {cout << "[C]" << endl;}
~A() {cout << "[~D]" << endl;}
A(A const& src) {cout << "[COPY]" << endl;}
A& operator=(A const& src) {cout << "[=}" << endl; return *this;}
void operator() () {cout << "#" << endl;}
};
void foo()
{
A a;
thread t{a};
t.join();
}
上面的输出:
[C]
[COPY]
[COPY]
[~D]
#
[~D]
[~D]
编辑:是的,添加移动构造函数后:
A(A && src) {cout << "[MOVE]" << endl;}
输出是这样的:
[C]
[COPY]
[MOVE]
[~D]
#
[~D]
[~D]