mardi 27 novembre 2018

Why would I ever need a move assignment operator?

Suppose I have a class A that has explicitly defined copy and move constructors and a destructor. Now it's time for me to define the assignment operators: copy and move.

For the copy constructor, I will use implement a non-throwing swap function and use that:

A& operator = (A const & a)
{
     A(a).swap(*this);
     return *this;
}

Now, why don't I replace the manual copying with passing the parameter by value?

A& operator = (A a)
{
     swap(a);
     return *this;
}

So far, so good. Now all I need to do is define the move assignment operator to complete the rule of 5. But do I really need to do that? In a scenario where I need to move-assign something, that something will be moved to the parameter a of my copy-assignment operator via the move constructor and then simply swapped with *this, which is a non-throwing fast operation.

Are there any drawbacks/caveats to my approach? If we have defined a good copy-assignment operator that uses the copy-and-swap idiom, why would we ever need a separate move assignment?

Aucun commentaire:

Enregistrer un commentaire