when是const引用比c ++ 11中的pass-by-value更好 [英] when is const reference better than pass-by-value in c++11

查看:193
本文介绍了when是const引用比c ++ 11中的pass-by-value更好的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一些前c ++ 11代码,其中我使用 const 引用传递大型参数,如向量'sa lot。示例如下:

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功能, code> 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];
}

例如, answer


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引用复杂的扣除模板参数,

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.

非常感谢,

推荐答案

通过值的一般经验法则是,当你最终会做一个复制。也就是说,而不是这样做:

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中是部分真实的,并且对于移动语义变得更有用,因为当以右值调用该函数时,可以用在pass-by-val情况下的移动来替换副本

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.

这篇关于when是const引用比c ++ 11中的pass-by-value更好的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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