std::thread Why object is copied twice?中接受的答案没有回答我对此的疑问,因此我再次在这里提问。 请不要将其标记为重复项。这是链接中的代码(贷记到Krzysztof):
#include <iostream>
#include <thread>
using namespace std;
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; }
};
int main() {
A a;
thread t{a};
t.join();
}
上面的输出
[C]
[COPY]
[COPY]
[~D]
#
[~D]
[~D]
我知道std::thread
会盲目复制传递给它的参数(除非您使用std::ref
或std::move
),所以这解释了第一个副本ctor
。但是,一旦将参数复制到线程的内部存储中,为什么再次调用副本ctor
?函子是否需要实例化两次?还是与std::thread
将复制的参数变成右值或其他东西有关?我真的迷失了。
顺便说一句,我不是正在寻找涉及移动语义的答案,即我需要使用ctor/pass
实现移动std::move()
,我想知道为什么,在将函子按值传递给std::thread ctor
的特定情况下,,函子的副本ctor
被调用了两次。对于我的用例,我必须按值传递函子。