I saw many code implementing rule of five in terms of copy and swap, but I think we can use a move function to replace the swap function as in the following code:
The only (small) problem with your code is the duplication of functionality between move_to_this()
and the destructor, which is a maintenance issue should your class need to be changed. Of course it can be solved by extracting that part into a common function destroy()
.
My critique of the "problems" discussed by Scott Meyers in his blog post:
He tries to manually optimize where the compiler could do an equally good job if it is smart enough. The rule-of-five can be reduced to the rule-of-four by
This automatically solves the problem of the resources of the left-hand-side object being swapped into the right-hand-side object and not being immediately released if the right-hand-side object is not a temporary.
Then, inside the implementation of the copy assignment operator according to the copy-and-swap idiom, swap()
will take as one of its arguments an expiring object. If the compiler can inline the destructor of the latter, then it will definitely eliminate the extra pointer assignment - indeed, why save the pointer that is going to be delete
ed on the next step?
My conclusion is that it is simpler to follow the well established idiom instead of slightly complicating the implementation for the sake of micro-optimizations that are well within the reach of a mature compiler.