Purpose of returning by const value?(按 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 值返回的目的?
基础教程推荐
- 您如何将 CreateThread 用于属于类成员的函数? 2021-01-01
- 设计字符串本地化的最佳方法 2022-01-01
- 调用std::Package_TASK::Get_Future()时可能出现争用情况 2022-12-17
- 什么是T&&(双与号)在 C++11 中是什么意思? 2022-11-04
- C++ 程序在执行 std::string 分配时总是崩溃 2022-01-01
- 如何在 C++ 中处理或避免堆栈溢出 2022-01-01
- C++,'if' 表达式中的变量声明 2021-01-01
- C++ 标准:取消引用 NULL 指针以获取引用? 2021-01-01
- 如何定义双括号/双迭代器运算符,类似于向量的向量? 2022-01-01
- 运算符重载的基本规则和习语是什么? 2022-10-31