c ++-const成员func,只能使用ref限定符在左值实例上调用 [英] c++ - const member func, that can be called upon lvalue instances only, using a ref-qualifier
问题描述
我正在尝试通过ref限定符强制在类的仅左值实例上调用类的const'getter'方法,并且由于某种原因得到了意外的结果(我正在通过 c ++ 1z 标志在 Windows C ++ 17 支持的 clang 6.0.1 进行编译>):
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):
声明 bool getVal()const&
允许在右值引用上也调用该方法.
The declaration bool getVal() const &;
allows the method to be called on rvalue references also.
声明 bool getVal()& ;;
据我了解,不允许在右值引用BUT上调用该方法-该函数不再是const方法,对于"getter"方法而言,这在设计上是有问题的
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?
推荐答案
使用 bool getVal()const&
,但为右值添加已删除的重载:
Use bool getVal() const &;
, but add a deleted overload for rvalues:
bool getVal() const && = delete;
这篇关于c ++-const成员func,只能使用ref限定符在左值实例上调用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!