为什么构造std :: thread时参数要移动两次?

问题描述 投票:2回答:1
考虑该程序,该程序实质上创建了以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()。因此,我希望

一个副本结构

一个动作结构为什么要进行第二步构造?

考虑该程序,该程序实质上创建了以arg为参数调用函数func()的std :: thread:#include

#include struct foo {foo()= default; ...

c++ c++11 move stdthread
1个回答
0
投票
这是因为您的func按值使用其参数。更改为任一

void func(const foo &){}

© www.soinside.com 2019 - 2024. All rights reserved.