mercredi 20 mai 2020

Implicit move constructor and assignment operator

What does it mean that implicit move constructor does a member-wise move and implicit move assignment operator a member-wise assignment?

From https://en.cppreference.com/w/cpp/language/move_constructor:

For non-union class types (class and struct), the move constructor performs full member-wise move of the object's bases and non-static members, in their initialization order, using direct initialization with an xvalue argument. If this satisfies the requirements of a constexpr constructor, the generated move constructor is constexpr.

From https://en.cppreference.com/w/cpp/language/move_assignment:

For non-union class types (class and struct), the move assignment operator performs full member-wise move assignment of the object's direct bases and immediate non-static members, in their declaration order, using built-in assignment for the scalars, memberwise move-assignment for arrays, and move assignment operator for class types (called non-virtually).

Can those implicit members look like this for the following exemplary class template:

template<class T>
class Holder {
public:
    Holder(int size) : m_size(size) { m_data = new T[m_size]; }

    Holder(Holder && other) :
        m_size(std::move(other.m_size)),
        m_data(std::move(other.m_data))
    {}

    Holder& operator=(Holder && other) {
       if(this == &other) return *this;
       m_data = std::move(other.m_data);
       m_size = std::move(other.m_size);
       return *this;
    }

    ~Holder() { delete [] m_data; }
private:
    T* m_data;
    int m_size;
};

What's more, what will the std::move() in the above example transfer the resources?

Aucun commentaire:

Enregistrer un commentaire