Purpose of returning by const value?
This question already has an answer here:
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();
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.
It's pretty pointless to return a const
value from a function.
It's difficult to 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.
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:
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.
上一篇: 运算符“<<”重载返回类型
下一篇: 通过const值返回的目的?