FAQ 14.11 When should const not be used in declaring a function return type?A function that returns its result by value should generally avoid const in the return type. For example, replace const Fred f() with either Fred f() or const Fred& f(). Using const Fred f() can be confusing to users, especially in the idiomatic case of copying the return result into a local. The exception to this rule is when users apply a const-overloaded member function directly to the temporary returned from the function. An example follows. #include <iostream> using namespace std; class Fred { public: void wilma() throw() { cout << "Fred::wilma()\n"; } void wilma() const throw() { cout << "Fred::wilma() const\n"; } }; Fred f() throw() { cout << "f(): "; return Fred(); } const Fred g() throw() { cout << "g(): "; return Fred(); } int main() { f().wilma(); <-- 1 g().wilma(); <-- 2 }
Because f() returns a non-const Fred, f().wilma() invokes the non-const version of Fred::wilma(). In contrast, g() returns a const Fred, so g().wilma() invokes the const version of Fred::wilma(). Thus, the output of this program is as follows. f(): Fred::wilma() g(): Fred::wilma() const |