C++ 通过 const 值返回的目的?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8716330/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Purpose of returning by const value?
提问by Praxeolitic
What is the purpose of the const in this?
这个 const 的目的是什么?
const Object myFunc(){
return myObject;
}
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.
我刚刚开始阅读 Effective C++,第 3 条提倡这一点,谷歌搜索得到了类似的建议,但也有反例。我看不出在这里使用 const 会有什么好处。假设按值返回是可取的,我认为没有任何理由保护返回的值。给出的为什么这可能有用的示例是防止返回值的意外 bool 转换。那么实际的问题是应该使用显式关键字来防止隐式 bool 类型转换。
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 可以防止在没有赋值的情况下使用临时对象。所以我无法用这些对象执行算术表达式。似乎从来没有一个未命名的 const 有用的情况。
What is gained by using const here and when would it be preferable?
在这里使用 const 有什么好处,什么时候更可取?
EDIT: Change arithmetic example to any function that modifies an object that you might want to perform before an assignment.
编辑:将算术示例更改为修改您可能希望在赋值之前执行的对象的任何函数。
回答by Kerrek SB
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:
在假设情况下,您可以对对象执行潜在的昂贵的非常量操作,通过 const-value 返回可防止您意外地在临时上调用此操作。想象一下,它+
返回了一个非常量值,你可以这样写:
(a + b).expensive();
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.
然而,在 C++11 时代,强烈建议将值作为非常量返回,以便您可以充分利用右值引用,这仅对非常量右值有意义。
In summary, there isa rationale for this practice, but it is essentially obsolete.
总之,就是这种做法的理由,但它本质上是过时的。
回答by Lightness Races in Orbit
It's prettypointlessto return a const
value from a function.
It's difficultto get it to have any effect on your code:
这是很难得到它会对你的代码有任何影响:
const int foo() {
return 3;
}
int main() {
int x = foo(); // copies happily
x = 4;
}
and:
和:
const int foo() {
return 3;
}
int main() {
foo() = 4; // not valid anyway for built-in types
}
// error: lvalue required as left operand of assignment
Though you can notice if the return type is a user-defined type:
struct T {};
const T foo() {
return T();
}
int main() {
foo() = T();
}
// error: passing ‘const T' as ‘this' argument of ‘T& T::operator=(const T&)' discards qualifiers
it's questionable whether this is of any benefit to anyone.
这是否对任何人都有好处是值得怀疑的。
Returning a reference is different, but unless Object
is some template parameter, you're not doing that.
返回引用是不同的,但除非Object
是某个模板参数,否则您不会这样做。
回答by Grizzly
It makes sure that the returned object (which is an RValue at that point) can't be modified. This makes sure the user can't do thinks like this:
它确保无法修改返回的对象(此时是 RValue)。这确保用户不能做这样的思考:
myFunc() = Object(...);
That would work nicely if myFunc
returned by reference, but is almost certainly a bug when returned by value (and probably won't be caught by the compiler). Of course in C++11 with its rvalues this convention doesn't make as much sense as it did earlier, since a const object can't be moved from, so this can have pretty heavy effects on performance.
如果myFunc
通过引用返回,这会很好地工作,但在通过值返回时几乎可以肯定是一个错误(并且可能不会被编译器捕获)。当然,在带有右值的 C++11 中,此约定不像以前那样有意义,因为无法移动 const 对象,因此这会对性能产生相当大的影响。
回答by Steven Feldman
It could be used as a wrapper function for returning a reference to a private constant data type. For example in a linked list you have the constants tail and head, and if you want to determine if a node is a tail or head node, then you can compare it with the value returned by that function.
它可以用作返回对私有常量数据类型的引用的包装函数。例如,在链表中,您有常量 tail 和 head,如果您想确定一个节点是尾节点还是头节点,则可以将其与该函数返回的值进行比较。
Though any optimizer would most likely optimize it out anyway...
尽管任何优化器很可能无论如何都会优化它......