samedi 21 novembre 2020

Returning Rvalue Reference to assign to a Lvalue

class X{
  public:
  int a;
  int b;
  X(){}
  X(int a,int b=0):a(a),b(b){}
}; 

X&& operator+(const X& a,const X& b){ 
  return move(X((a.a+b.a),(a.b+b.b)));
  //return move(x);
}

int main(){
  X a(2,1);

  X c = 7+a;      //WORKS! WHY???
  X &&c = 7+a     //DOES NOT WORK 

  cout<<c.a<<" "<<c.b<<endl;
  return 0;
}

As I know and also mentioned in the other answers, the returned reference(of any type) should be invalid. But in case of c = 7+a works unexpectedly, while &&c = 7+a does not work(as expected). Why???

The returned Rvalue Reference in the first case is supposed to passed to the copy constructor of class X and hence the copy to c should fail, right?

Aucun commentaire:

Enregistrer un commentaire