简体   繁体   中英

Const and reference member function qualifiers

Let's say we have member class with two member functions defined as follows:

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;
}

I not quite understand what is the difference between const& and & . Why it works with getVarCLRef if we specified this function as const& ? Shouldn't it be allowed to be invoked only with lvalues?

getVarLRef , on the other hand, works just fine and fails to compile in this case as expected.

I use C++11 and gcc 7.3.0

Shouldn't it be allowed to be invoked only with lvalues?

Because rvalue could be bound to lvalue-reference to const too. Just as the following code works.

const SomeClass& r = SomeClass();

On the other hand, rvalue can't be bound to lvalue-reference to non- const , then the invocation of getVarLRef fails as you expected.

Const and reference member function qualifiers are to be able to apply those qualifier to " this " as for regular parameter, so mainly, you have something like:

int getVarLRef(SomeClass& self) { return self.val; }
int getVarCLRef(const SomeClass& self) { return self.val; }

And there, I think you know that:

getVarCLRef(SomeClass()); // Valid, temporary can bind to const lvalue reference
getVarLRef(SomeClass()); // INVALID, temporary CANNOT bind to non-const lvalue reference

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM