There is little value in adding const
qualifications to non-reference/non-pointer rvalues, and no point in adding it to built-ins.
In the case of user-defined types, a const
qualification will prevent callers from invoking a non-const
member function on the returned object. For example, given
const std::string foo();
std::string bar();
then
foo().resize(42);
would be forbidden, while
bar().resize(4711);
would be allowed.
For built-ins like int
, this makes no sense at all, because such rvalues cannot be modified anyway.
(I do remember Effective C++ discussing making the return type of operator=()
a const
reference, though, and this is something to consider.)
Edit:
It seems that Scott did indeed give that advice. If so, then due to the reasons given above, I find it questionable even for C++98 and C++03. For C++11, I consider it plainly wrong, as Scott himself seems to have discovered. In the errata for Effective C++, 3rd ed., he writes (or quotes others who complained):
The text implies that all by-value returns should be const, but cases where non-const by-value returns are good design are not difficult to find, e.g., return types of std::vector where callers will use swap with an empty vector to "grab" the return value contents without copying them.
And later:
Declaring by-value function return values const will prevent their being bound to rvalue references in C++0x. Because rvalue references are designed to help improve the efficiency of C++ code, it's important to take into account the interaction of const return values and the initialization of rvalue references when specifying function signatures.