jeudi 5 mars 2015

return and move constructor [duplicate]



This question already has an answer here:





struct CAT
{
CAT(){cout<<"CAT()"<<endl;}
CAT(const CAT& ){cout<<"CAT(const CAT&)"<<endl;}
CAT(CAT&& ){cout<<"CAT(CAT &&)"<<endl;}
void speak(){cout<<"speak()"<<endl;}
};


CAT f()
{
CAT local_c;
return local_c;
}

int main()
{
CAT c = f();
c.speak();
}


I compile the code using -fno-elide-constructors which disabling g++'s return-value optimisation, so we can observe all the actions in the code.


Here is the output:



CAT()
CAT(CAT &&)
CAT(CAT &&)
speak()


what is confusing me is that the first output "CAT(CAT &&)". It is my understanding that local_c is a lvalue, so when compiler create the internal temporary CAT object, it should use CAT(const CAT&) instead of CAT(CAT&&), right?




Aucun commentaire:

Enregistrer un commentaire