The implementations of the copy operator and copy constructor (not moving) are used with the swap() method function closed in operator=() , respectively, the copy constructor is also called in the operator to create a temporary object.

Now I add to the class a moving assignment operator and constructor. For example:

 MyClass::MyClass(MyClass&& other) { *this = std::move(other); // через оператор? } MyClass& MyClass::operator=(MyClass&& rhs) { rhs.swap(*this); // или this->swap(rhs); Solution().swap(rhs); // это ок return *this; } 

So I wonder if this implementation is optimal, in particular, here the operator is already using k, is that not bad? It is possible to make initialization lists in, for example:

 MyClass::MyClass(MyClass&& other) : value_1(std::move(other.value_1)), value_2(std::move(other.value_2)) {} 

Will it give any advantage? Please write what is the best option, in your opinion, the implementation of these two specials. functions.

    1 answer 1

     MyClass::MyClass(MyClass&& other) { *this = std::move(other); } 

    What will you do in this code if the class members are references, constants and objects of classes that do not have a default constructor? And nothing, it just will not be collected.

    Will it give any advantage?

    In the case of assignment, objects are already created, so the specific benefits depend on the members of the class. If class members have a hard initialization, then by the time of *this = std::move(other); they should already be created (if at all possible), which means we spent a lot of resources on completely unnecessary gestures.

    Please write what is the best option, in your opinion, the implementation of these two specials. functions.

    For starters, both do not interfere with add noexcept . Well, swap is still an exchange, i.e. the current object will simply move and will not be destroyed. Is this the behavior you expect in external code? On the other hand, is it necessary to destroy this object? Here, rather, it all depends on you. I would expect that the object that I’m replacing will disappear right away.