假设我们有一个成员类,其中的两个成员函数定义如下:
class SomeClass
{
private:
int val = {};
public:
const int getVarLRef() & {
return val;
}
const int getVarCLRef() const& {
return val;
}
};
int main()
{
auto var1 = SomeClass().getVarCLRef();
auto var2 = SomeClass().getVarLRef();
return 0;
}
我不太了解const&
和&
之间的区别。
如果我们将此功能指定为getVarCLRef
,为什么它可以与const&
一起使用?不应只允许使用左值调用它吗?
getVarLRef
可以正常工作,并且在这种情况下无法按预期进行编译。
我使用C ++ 11和gcc 7.3.0
答案 0 :(得分:2)
是否应该只允许使用左值调用?
因为右值也可以绑定到str = (new Regex(@"[^\w\\-]+")).Replace(str, ""); => result: tât
的左值引用。就像下面的代码一样。
const
另一方面,不能将rvalue绑定到非const SomeClass& r = SomeClass();
的lvalue-reference上,然后const
的调用会失败。
答案 1 :(得分:1)
常量和引用成员函数限定符应能够将那些限定符应用于常规参数“ this
”,因此,主要具有以下内容:
int getVarLRef(SomeClass& self) { return self.val; }
int getVarCLRef(const SomeClass& self) { return self.val; }
还有,我想你知道:
getVarCLRef(SomeClass()); // Valid, temporary can bind to const lvalue reference
getVarLRef(SomeClass()); // INVALID, temporary CANNOT bind to non-const lvalue reference