const和引用成员函数限定符

假设我们有一个成员类,其中的两个成员函数定义如下:

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

eeeeeeeeeeeeeeeeeed 回答:const和引用成员函数限定符

  

是否应该只允许使用左值调用?

因为右值也可以绑定到str = (new Regex(@"[^\w\\-]+")).Replace(str,""); => result: tât的左值引用。就像下面的代码一样。

const

另一方面,不能将rvalue绑定到非const SomeClass& r = SomeClass(); 的lvalue-reference上,然后const的调用会失败。

,

常量和引用成员函数限定符应能够将那些限定符应用于常规参数“ 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
本文链接:https://www.f2er.com/3008783.html

大家都在问