如果const引用也只花费一个副本,为什么在C ++ 11中建议按值传递(如果需要副本)? [英] Why is passing by value (if a copy is needed) recommended in C++11 if a const reference only costs a single copy as well?

查看:76
本文介绍了如果const引用也只花费一个副本,为什么在C ++ 11中建议按值传递(如果需要副本)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图理解移动语义,右值引用,std::move等.我一直试图通过搜索该站点上的各种问题来弄清楚为什么不建议通过const std::string &name + _name(name)std::string name + _name(std::move(name))(如果需要复制).

I am trying to understand move semantics, rvalue references, std::move, etc. I have been trying to figure out, by searching through various questions on this site, why passing a const std::string &name + _name(name) is less recommended than a std::string name + _name(std::move(name)) if a copy is needed.

如果我理解正确,则以下内容需要一个副本(通过构造函数)加上一个移动(从临时对象到成员):

If I understand correctly, the following requires a single copy (through the constructor) plus a move (from the temporary to the member):

Dog::Dog(std::string name) : _name(std::move(name)) {}

另一种(老式的)方法是通过引用传递它并将其复制(从引用到成员):

The alternative (and old-fashioned) way is to pass it by reference and copy it (from the reference to the member):

Dog::Dog(const std::string &name) : _name(name) {}

如果第一种方法需要一个副本并同时移动两个副本,而第二种方法只需要一个副本,那么第一种方法又会如何被优先使用,并且在某些情况下会更快?

If the first method requires a copy and move both, and the second method only requires a single copy, how can the first method be preferred and, in some cases, faster?

推荐答案

使用数据时,您需要一个可以使用的对象.当您获得std::string const&时,您将 必须复制该对象,而与是否需要该参数无关.

When consuming data, you'll need an object you can consume. When you get a std::string const& you will have to copy the object independent on whether the argument will be needed.

当按值传递对象时,如果必须复制该对象,即当传递的对象不是临时对象时,将复制该对象.但是,如果碰巧是临时的,则可以在适当的位置构造对象,即,任何副本都可能被删除了,您只需为移动构造付费.也就是说,有可能实际上没有任何副本.

When the object is passed by value the object will be copied if it has to be copied, i.e., when the object passed is not a temporary. However, if it happens to be a temporary the object may be constructed in place, i.e., any copies may have been elided and you just pay for a move construction. That is, there is a chance that no copy actually happens.

这篇关于如果const引用也只花费一个副本,为什么在C ++ 11中建议按值传递(如果需要副本)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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