Search code examples
c++pointersconstructordeep-copyshallow-copy

C++ copy constructor, can anyone explain why?


using namespace std;

class C {

public:

    char *s;

    C(const char *s0) {
        s = new char[strlen(s0)+1];
        strcpy(s,s0);
    }

    C(C &c) {
        s = new char[strlen(c.s)+1];
        strcpy(s,c.s);
    }
};

int main(int argc, char* argv[]) {

    C c("cde");
    C c0(c);

    cout << c.s << endl;
    cout << c0.s << endl;

    c.s[1] = 'X';

    cout << c.s << endl;
    cout << c0.s << endl;
}

I'm not so sure what is happening with the pointers and references. Can anyone explain why the output for the second c0.s is still "cde"? Thank you.


Solution

  • The copy constructor is creating a new buffer

    s = new char[strlen(c.s)+1];
    

    and copying the contents of the original's buffer into the new buffer

    strcpy(s,c.s);
    

    so both objects contain separate buffers. Modification of one object modifies that object's buffer, so no modifications bleed over to the other object.

    If the copy constructor looked something like this

    C(C &c) {
        s = c.s;
    }
    

    replicating the default copy behaviour, both objects would refer to the same buffer and changes to one would appear in the other.

    If a destructor had been implemented to delete the buffer and prevent leakage of the storage allocated to the buffer, this would be fatal. destroying one object would release the buffer for both and sooner or later the invalid buffer would either be accessed or deleted.

    For more read What is The Rule of Three?