FAQ 14.11 When should const not be used in declaring a function return type?

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 } 

(1) Calls the non-const version of the wilma() member function

(2) Calls the const version of the wilma() member function

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 


C++ FAQs
C Programming FAQs: Frequently Asked Questions
ISBN: 0201845199
EAN: 2147483647
Year: 2005
Pages: 566
Authors: Steve Summit

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net