C/C++ Arena

Step 4 of 8

The copy problem

By default, copying an object copies each member. For IntArray that copies the pointer, so two objects share one array. When both destructors run, the array is deleted twice (a crash, or worse).

Fix it by writing a copy constructor that makes a deep copy:

IntArray(const IntArray& other)
    : data_(new int[other.n_]), n_(other.n_) {
    for (int i = 0; i < n_; i++) data_[i] = other.data_[i];
}

This is the rule of three: if a class needs a destructor, it almost always needs a copy constructor and copy assignment too.

Your turn: add the deep-copy constructor. (Copy assignment is provided.)

Previous: RAII Next: Non-copyable classes