c++visual-c++c++17ref-qualifier

c++ - const member func, that can be called upon lvalue instances only, using a ref-qualifier


I'm trying to enforce a const 'getter' method of a class to be called upon only lvalue instances of the class, via a ref-qualifier and for some reason getting an unexpected result (I'm compiling with clang 6.0.1 with C++ 17 support, via c++1z flag, on Windows):

The declaration bool getVal() const &; allows the method to be called on rvalue references also.

The declaration bool getVal() &; doesn't allow the method to be called on rvalue references BUT, as I understand - the function isn't a const method no more, which is problematic, design-wise, for a 'getter' method.

What's the right way to get both characteristics for a method?


Solution

  • Use bool getVal() const &;, but add a deleted overload for rvalues:

    bool getVal() const && = delete;