const引用何时比C ++ 11中的按值传递更好? [英] When is a const reference better than pass-by-value in C++11?

查看:119
本文介绍了const引用何时比C ++ 11中的按值传递更好?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一些C ++ 11以前的代码,在其中我使用 const 引用传递诸如 vector 很多。一个示例如下:

I have some pre-C++11 code in which I use const references to pass large parameters like vector's a lot. An example is as follows:

int hd(const vector<int>& a) {
   return a[0];
}

我听说使用新的C ++ 11功能,您可以通过 vector 的值如下所示,而不会影响性能。

I heard that with new C++11 features, you can pass the vector by value as follows without performance hits.

int hd(vector<int> a) {
   return a[0];
}

例如,这个答案


C ++ 11的移动语义使按值传递和返回的内容更多

C++11's move semantics make passing and returning by value much more attractive even for complex objects.

上面两个选项在性能上是否相同是真的吗?

Is it true that the above two options are the same performance-wise?

如果是这样,何时在选项1中使用const引用比在选项2中更好? (即为什么我们仍然需要在C ++ 11中使用const引用)。

If so, when is using const reference as in option 1 better than option 2? (i.e. why do we still need to use const references in C++11).

我问的一个原因是const引用使模板参数的推导变得复杂,并且如果与const引用性能相同,则仅使用按值传递要容易得多。

One reason I ask is that const references complicate deduction of template parameters, and it would be a lot easier to use pass-by-value only, if it is the same with const reference performance-wise.

推荐答案

按值传递的一般经验法则是,无论如何您最终都会生成 copy 。就是说,而不是这样做:

The general rule of thumb for passing by value is when you would end up making a copy anyway. That is to say that rather than doing this:

void f(const std::vector<int>& x) {
    std::vector<int> y(x);
    // stuff
}

首先通过const-ref和然后复制它,而应该执行以下操作:

where you first pass a const-ref and then copy it, you should do this instead:

void f(std::vector<int> x) {
    // work with x instead
}

在C ++ 03中部分正确,并且在move语义上变得更加有用,因为在使用右值调用函数时,在传递值情况下,副本 可能会被move替换为

This has been partially true in C++03, and has become more useful with move semantics, as the copy may be replaced by a move in the pass-by-val case when the function is called with an rvalue.

否则,当您只想读取数据时,仍然首选通过 const 引用传递,高效的方式。

Otherwise, when all you want to do is read the data, passing by const reference is still the preferred, efficient way.

这篇关于const引用何时比C ++ 11中的按值传递更好?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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