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

醉酒当歌 提交于 2021-02-05 07:48:31

问题


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?


回答1:


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

bool getVal() const && = delete;


来源:https://stackoverflow.com/questions/62609367/c-const-member-func-that-can-be-called-upon-lvalue-instances-only-using-a

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!