std :: bind和std :: thread总是复制参数的基本原理是什么? [英] What is the rationale behind std::bind and std::thread always copying arguments?

查看:1305
本文介绍了std :: bind和std :: thread总是复制参数的基本原理是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

很清楚,std :: bind和std :: thread的默认行为是它将复制(或移动)传递给它的参数,并且要使用引用语义,我们必须使用引用包装器。 / p>

It's pretty well known that the default behaviour of std::bind and std::thread is that it will copy (or move) the arguments passed to it, and to use reference semantics we will have to use reference wrappers.


  1. 有人知道为什么这会产生良好的默认行为吗? Esp。在C ++ 11中使用右值引用和完美转发,在我看来,更好地转发参数更有意义。

  1. Does anyone know why this makes a good default behaviour? Esp. in C++11 with rvalue reference and perfect forwarding, it seems to me that it makes more sense to just perfectly forward the arguments.

std :: make_shared虽然不总是复制/移动,但只是完美地向前提供的参数。为什么在这里有两个看似不同的转发参数的行为? (std :: thread和std :: bind,总是复制/移动vs std :: make_shared不要)

std::make_shared though doesn't always copy/move but just perfectly forward the provided arguments. Why are there two seemingly different behaviour of forwarding arguments here? (std::thread and std::bind that always copy/move vs std::make_shared that don't)


推荐答案

make_shared 转发到正在被调用的构造函数 。如果构造函数使用调用引用语义,它将获得引用;如果它通过值调用,它会做一个副本。

make_shared forwards to a constructor that is being called now. If the constructor uses call by reference semantics, it will get the reference; if it does call by value, it will make a copy. No problem here either way.

bind 会创建一个对函数的延迟调用,该函数在某些未知点调用未来,当地方上下文可能走了。如果 bind 使用完美转发,则必须复制通常通过引用发送的参数,并且在实际调用时不知道是实时的, store他们在某个地方,并管理该存储。用当前语义 bind 为你。

bind creates a delayed call to a function that is called at some unknown points in the future, when the local context is potentially gone. If bind were using perfect forwarding, you would have to copy the arguments that are normally sent byreference and not known to be live at the time of the actual call, store them somewhere, and manage that storage. With the current semantics bind does it for you.

这篇关于std :: bind和std :: thread总是复制参数的基本原理是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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