c++ - 为什么在构造 std::thread 时参数 move 了两次

标签 c++ c++11 move stdthread

考虑这个基本上创建 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/

相关文章:

c++ - 如何: TBB node with multiple asynchronous inputs and multiple outputs

具有函数的类的c++ sizeof()

c++ - 多重集 lower_bound 迭代器的位置

c++ - 智能指针列表 - 管理对象生命周期和指针有效性

c++ - 匿名 union 中类成员的初始化

c++ - 最佳C++ move 构造函数实现实践

c++ - 预编译头文件是否可以用作将被静态链接的库的一部分?

c++ - 断言 double 可以放入 int

git - 将 git 本地存储库(从中克隆)提升到 origin 以与 git-tf 一起使用的最佳方法

swift - 在靠近特定点时降低节点速度