mardi 1 janvier 2019

Shared code between copy constructor and assignment operator

class X {

  public:
    X(X& x) {
        allocateMem();
        copyData(x);
    }

    X& operator = (const X& rhs) {
        freeMem();
        copyData(rhs);
        return *this;
    }

}

I'm new to c++, and I have been told that it's a bad idea to call the copy constructor from the assignment operator, however can I reuse the data initialization part between copy and assignment? is the above code acceptable? What are the cons of this way of writing copy and assignment?

Aucun commentaire:

Enregistrer un commentaire