为什么构造std :: thread时参数会移动两次 [英] Why arguments moved twice when constructing std::thread

查看:57
本文介绍了为什么构造std :: thread时参数会移动两次的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Consider this program that essentially creates std::thread that calls the function func() with arg as argument:

#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().因此,我希望一个副本结构一个移动结构.

As far as I understand arg is copied internally in the thread object and then passed to func() as an rvalue (moved). So, I expect one copy construction and one move construction.

为什么要进行第二步施工?

Why is there a second move construction?

推荐答案

您通过值将参数传递给func,这应该构成第二步.显然,std::thread在调用func之前在内部又存储了一次,根据标准,AFAIK是绝对合法的.

You pass argument to func by value which should constitute the second move. Apparently std::thread stores it internally one more time before calling func, which AFAIK is absolutely legal in terms of the Standard.

这篇关于为什么构造std :: thread时参数会移动两次的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆