按 const 值返回的目的?

Purpose of returning by const value?(按 const 值返回的目的?)

本文介绍了按 const 值返回的目的?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这个const的目的是什么?

What is the purpose of the const in this?

const Object myFunc(){
    return myObject;
}

我刚开始阅读 Effective C++,第 3 条提倡​​这一点,谷歌搜索会找到类似的建议,但也有反例.我看不出在这里使用 const 会更好.假设按值返回是可取的,我认为没有任何理由保护返回的值.给出的示例说明为什么这可能会有所帮助,以防止对返回值进行意外的 bool 强制转换.那么实际的问题是应该使用显式关键字来防止隐式布尔转换.

I've just started reading Effective C++ and Item 3 advocates this and a Google search picks up similar suggestions but also counterexamples. I can't see how using const here would ever be preferable. Assuming a return by value is desirable, I don't see any reason to protect the returned value. The example given for why this might be helpful is preventing unintended bool casts of the return value. The actual problem then is that implicit bool casts should be prevented with the explicit keyword.

在这里使用 const 可以防止使用没有赋值的临时对象.所以我不能用这些对象执行算术表达式.似乎从来没有一个未命名的 const 有用的情况.

Using const here prevents using temporary objects without assignment. So I couldn't perform arithmetic expressions with those objects. It doesn't seem like there's ever a case that an unnamed const is useful.

在这里使用 const 有什么好处,什么时候更可取?

What is gained by using const here and when would it be preferable?

将算术示例更改为修改您可能希望在赋值之前执行的对象的任何函数.

Change arithmetic example to any function that modifies an object that you might want to perform before an assignment.

推荐答案

在假设的情况下,你可以对一个对象执行一个潜在的昂贵的非常量操作,通过 const-value 返回可以防止你不小心在一个对象上调用这个操作暂时的.想象一下 + 返回一个非常量值,你可以这样写:

In the hypothetical situation where you could perform a potentially expensive non-const operation on an object, returning by const-value prevents you from accidentally calling this operation on a temporary. Imagine that + returned a non-const value, and you could write:

(a + b).expensive();

然而,在 C++11 时代,强烈建议将值作为非常量返回,以便您可以充分利用仅对非常量右值有意义的右值引用.

In the age of C++11, however, it is strongly advised to return values as non-const so that you can take full advantage of rvalue references, which only make sense on non-constant rvalues.

总之,这种做法一个基本原理,但它基本上已经过时了.

In summary, there is a rationale for this practice, but it is essentially obsolete.

这篇关于按 const 值返回的目的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:按 const 值返回的目的?

基础教程推荐