Which to use: move assignment operator vs copy assignment operator

后端 未结 2 787
孤独总比滥情好
孤独总比滥情好 2021-02-08 18:14

I don\'t seem to get why would you use the move assignment operator:

CLASSA & operator=(CLASSA && other); //move assignment operator
         


        
2条回答
  •  借酒劲吻你
    2021-02-08 18:43

    You are not comparing like-with-like

    If you are writing a move-only type like std::unique_ptr then a move assignment operator would be your only choice.

    The more typical case is where you have a copyable type in which case I think you have three options.

    1. T& operator=(T const&)
    2. T& operator=(T const&) and T& operator=(T&&)
    3. T& operator=(T) and move

    Note that having both the overloads you suggested in one class is not an option as it would be ambiguous.

    Option 1 is the traditional C++98 option and will perform fine in most cases. However, if you need to optimize for r-values you could consider Option 2 and add a move assignment operator.

    It is tempting to consider Option 3 and pass-by-value and then move which I think is what you are suggesting. In that case you only have to write one assignment operator. It accepts l-values and at the cost of only one extra move accepts r-values and many people will advocate this approach.

    However, Herb Sutter pointed out in his "Back to the Basics! Essentials of Modern C++ Style" talk at CppCon 2014 that this option is problematic and can be much slower. In the case of l-values it will perform an unconditional copy and will not reuse any existing capacity. He provides numbers to backup his claims. The only exception is constructors where there is no existing capacity to reuse and you often have many parameters so pass by-value can reduce the number of overloads needed.

    So I would suggest you start with Option 1 and move to Option 2 if you need to optimize for r-values.

提交回复
热议问题