Should I return bool or const bool?

后端 未结 11 901
我在风中等你
我在风中等你 2021-01-01 10:36

Which is better:

bool MyClass::someQuery() const;

const bool MyClass::someQuery() const;

I\'ve been using \'const bool\' since I\'m sure I

11条回答
  •  星月不相逢
    2021-01-01 11:00

    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
    

提交回复
热议问题