Should I return bool or const bool?

后端 未结 11 825
我在风中等你
我在风中等你 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 10:58

    This is the case when const adds no value but inflates the code and makes the reader think more. What's the point of this const? The caller can copy the value into some non-const variable and do whatever he wants with it anyway.

    0 讨论(0)
  • 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
    
    0 讨论(0)
  • 2021-01-01 11:00

    When you returning a refernce to a member variable it makes sense to make it const. Here you are returning a copy, hence there is no need of const.

    0 讨论(0)
  • 2021-01-01 11:02

    Note that if((a*b) = c) won't compile for built-in types anyway, so it is very relevant here whether we're talking built-in types (your question asks for bool) or user-defined types.

    For built-in types it makes no sense at all, so it shouldn't be used. And for user-defined types, I'm in jalf's camp: What if the caller wants to modify the returned object?

    I'm not convinced that if((a*b) = c) is such a good argument for returning const user-defined types, since I can't remember the last time I've seen a compiler not warn about this.

    0 讨论(0)
  • 2021-01-01 11:02

    As bool is going to be copied, it's the same, to put const or not. Plus you'll may have some compil problems.

    0 讨论(0)
  • 2021-01-01 11:08

    It completely doesn't matter. Therefore, the consensus is to return just bool.

    The reason that it doesn't matter is that you can't call non-const member functions anyway; bool is not a class or struct.

    0 讨论(0)
提交回复
热议问题