The efficient way to write move copy and move assignment constructors

前端 未结 3 1727
长情又很酷
长情又很酷 2021-01-05 23:57

Are the following assignment and copy move constructors the most efficient? if anybody have other way please tell me? I mean what bout std::swap? and calling assignment th

3条回答
  •  再見小時候
    2021-01-06 00:34

    You don't need so many swaps and assignments in your move constructor. This:

    Widget(Widget&& other) :
        length( other.length_ ), data( other.data_ )
    {
        other.length_ = 0;
        other.data_ = nullptr;
    }
    

    does the minimum work for the move constructor: 4 assignments in total. Your version had 8, counting the ones in the calls to swap().

    Your move assignment is OK, but you might want to consider just writing one operator=() to cover both cases:

    Widget &operator=( Widget other ) {
        delete data_;
        data_ = other.data_;
        other.data_ = nullptr;
        length_ = other.length_;
        other.length_ = 0;
        return *this;
    }
    

    This is slightly less efficient than your version, in that it can move twice.

提交回复
热议问题