samedi 28 novembre 2015

In C++ class with copy & move ctor and copy assignment: no need for move assignment?

If I have a C++ class with copy and move constructors and copy assignment like so:

class Foo {
public:
    int A[];

    // custom ctor
    Foo(size_t N) {
        A = new A[N];
        for(int i = 0; i < N; i++) A[i] = i * i;
    }

    // copy ctor
    Foo(Foo& other) {
        size_t N = sizeof(other.A) / sizeof(int);
        A = new A[N];
        for(int i = 0; i < N; i++) A[i] = other.A[i];
    }

    // move ctor
    Foo(Foo&& other) {
        A = other.A;
        other.A = nullptr;
    }

    // copy assignment AND move assignment?
    Foo& operator=(Foo other) {
        std::swap(this.A, other.A);
        return *this;
    }

    // default dtor
    ~Foo() {
        delete[] A;
    }

Can I in this case simply avoid defining a move assignment operator and assume that still move assignment is taking place when possible? My reasoning behind that is: the copy assignment operator has to construct the Foo object defined as parameter. Now it can choose between the copy ctor and the move ctor as both are available. Thus if given an rvalue it should choose the move ctor and if given an lvalue it should choose the copy ctor. Is this correct?

Also: will this implementation work regarding the sizeof calculation of the array? If not, why not?

Aucun commentaire:

Enregistrer un commentaire