Const 和引用成员函数限定符
Const and reference member function qualifiers
假设我们有成员class,其中两个成员函数定义如下:
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&
和&
有什么区别。
如果我们将此函数指定为 const&
,为什么它与 getVarCLRef
一起使用?难道不应该只允许用左值调用吗?
另一方面,getVarLRef
工作正常,在这种情况下无法按预期编译。
I use C++11 and gcc 7.3.0
Shouldn't it be allowed to be invoked only with lvalues?
因为右值也可以绑定到 const
的左值引用。就像下面的代码一样有效。
const SomeClass& r = SomeClass();
另一方面,右值不能绑定到非const
的左值引用,然后 getVarLRef
的调用如您所料失败。
Const 和 reference 成员函数限定符能够将这些限定符应用于“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
假设我们有成员class,其中两个成员函数定义如下:
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&
和&
有什么区别。
如果我们将此函数指定为 const&
,为什么它与 getVarCLRef
一起使用?难道不应该只允许用左值调用吗?
getVarLRef
工作正常,在这种情况下无法按预期编译。
I use C++11 and gcc 7.3.0
Shouldn't it be allowed to be invoked only with lvalues?
因为右值也可以绑定到 const
的左值引用。就像下面的代码一样有效。
const SomeClass& r = SomeClass();
另一方面,右值不能绑定到非const
的左值引用,然后 getVarLRef
的调用如您所料失败。
Const 和 reference 成员函数限定符能够将这些限定符应用于“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