I have a bit confusion about this code:
struct A
{
A& bar()&&;
};
A& A::bar()&&
{
std::cout << "A::bar()&&\n";
return *this;
}
int main()
{
A{}.bar();// called by an rvalue
}
So what I understand is that bar
can be called only by a modifiable-rvalue. Until this it is OK. But how can bar
return a non-constant lvalue reference to that rvalue?
bar()
binds and returns a modifiable lvalue reference to that rvalue object?The reason is that the this
pointer for a class C
can be either C*
or const C*
- not C& *
or C&& *
(those aren't actual types; you can't declare a C& * ptr
). So, even when your method runs for an rvalue instance of class A
, you get one of those two (GodBolt). And when you apply the *
operator, you get an lvalue, not an rvalue.