lundi 5 janvier 2015

Implementing move assignment in terms of destructor and move constructor

Say I have a class which manages memory and thus needs user-defined special member functions (imagine vector or similar).


Consider the following implementation of the move-assignment operator:



Class& operator=(Class&& rhs)
{
this->~Class(); // call destructor
new (this) Class(std::move(rhs)); // call move constructor in-place
}




  1. Is it valid to implement a move-assignment operator this way? That is, does calling a destructor and constructor in this way not run afoul of any object lifetime rules in the language?




  2. Is it a good idea to implement a move-assignment operator this way? If not, why not, and is there a better canonical way?




Aucun commentaire:

Enregistrer un commentaire