Should I return bool or const bool?

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

    To be a little more specific, only "objects" can be const. The C++ standard's definition of "object" includes everything an lvalue refers to ("has a name") and class-type temporaries. A boolean return value is an rvalue of a non-class type which is why a standards-compliant compiler will just ignore "const" in this case. As others said already, it's useless in this context.

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

    This is an ancient post, but I think it's worth mentioning there is a potential corner case here since C++11. While, as stated by others, it will make no difference whether you use const bool or bool as return type in most cases, if you are using C++11 decltype and associates, e.g. result_of, you could declare a variable with the same type as the returning value of some function, and so the const would actually have an effect in this case.

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

    const return type

    SUMMARY:

    The value of a return type that is declared const cannot be changed. This is especially usefull when giving a reference to a class’s internals, but can also prevent rarer errors.

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

    The const modifier is only used for return types that are returned by reference (either as reference const SomeObject& or via a pointer const SomeObject*), so the caller won't be able to modify the object via the reference/pointer. Primitive types are returned by value, which means that the caller receives a copy of the the object, not the object itself.

    Therefore, const is not really appropriate for returned value types. Since the copy is outside of the control of the called function, the called function should not dictate to the caller that it cannot be changed.

    0 讨论(0)
  • 2021-01-01 11:22
    const bool func();
    bool f = func();
    

    0 errors, 0 warnings. What have you accomplished other than unnecessary code inflation?

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