通过const值返回的目的? [英] Purpose of returning by const value?

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

问题描述

这里const的用途是什么?

What is the purpose of the const in this?

const Object myFunc(){
    return myObject;
}

我刚刚开始阅读Effective C ++,搜索选择类似的建议,但也反例。我不明白如何使用const这里将是更可取。假设按值返回是可取的,我没有看到任何理由保护返回的值。给出为什么这可能有帮助的例子是阻止返回值的意外bool转换。实际的问题是隐式bool转换应该用explicit关键字阻止。

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这里防止使用临时对象没有分配。所以我不能用这些对象执行算术表达式。

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. (This is my first post and wow, I can't believe how fast people put together good answers with code examples and potholed links, thanks!)

推荐答案

在假设的情况下,你可以对一个对象执行一个潜在的昂贵的非const操作,返回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的时代, const,所以你可以充分利用右值引用,这只对非常数右值有意义。

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值返回的目的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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