Search code examples
c++constantsreturn-value

Does it make sense to return fundamental types by const value?


Which is better:

bool MyClass::someQuery() const;

const bool MyClass::someQuery() const;

I've been using const bool since I'm sure I remember hearing it's "what the ints do" (for e.g. comparison operators) but I can't find evidence of that anywhere, mostly due to it being difficult to Google and IntelliSense not helping out any ;) Can anyone confirm that?

To me returning const values (this isn't just about bool) makes more sense; it'll prevent temporaries being modified, which is almost always going to be a programmer mistake. I just want something to back that up so I can extol returning const values to my colleagues :)


Solution

  • So you know it's right, you're just after the Voice of Authority? Preventing accidental modification of temporaries is very valuable. In general, you should declare as many things as you possibly can const, it protects you from a variety of accidents and gives the optimiser useful hints.

    D'you have a copy of Scott Meyers' "Effective C++" around? Point them at Item 3 (page 18 in the third edition) ;)

    It gives the example of

    class Rational {...};
    const Rational operator* (const Rational& lhs, const Rational& rhs );
    
    if( (a * b) = c ) // declaring operator *'s return value const causes error to be caught by compiler