考虑这个基本上创建 std::thread
的程序调用函数 func()
与 arg
作为论据:
#include <thread>
#include <iostream>
struct foo {
foo() = default;
foo(const foo&) { std::cout << "copy ctor" << std::endl; }
foo(foo&&) noexcept { std::cout << "move ctor" << std::endl; }
};
void func(foo){}
int main() {
foo arg;
std::thread th(func, arg);
th.join();
}
我的输出是
copy ctor
move ctor
move ctor
据我了解
arg
在线程对象内部复制,然后传递给 func()
作为右值( move )。所以,我希望 一式建筑和 一招施工 .为什么要进行二次施工?
最佳答案
您将参数传递给 func
按值(value),这应该构成第二个 Action 。显然 std::thread
在调用 func
之前在内部再存储一次,就标准而言,AFAIK 是绝对合法的。
关于c++ - 为什么在构造 std::thread 时参数 move 了两次,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59601840/