A better way to implement copy-and-swap idiom in C++11

后端 未结 2 1910
迷失自我
迷失自我 2021-02-03 10:12

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:



        
2条回答
  •  孤街浪徒
    2021-02-03 11:13

    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

    • providing only the copy assignment operator that takes its argument by value and
    • not bothering to write the move assignment operator (exactly what you did).

    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 deleteed 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.

提交回复
热议问题