Why you copy a MyClass
instance, the default-generator copy constructor is called. This just copies the internal a
pointer, and does not create a new int
array.
So when the copy is destroyed, it delete
s the array, and then when the original is destroyed, it also delete
s the array.
There are 2 ways around this:
- Preferable: use something that wraps up all the allocation and copying for you, such as
std::vector
(rule of 0, we'll come to that in a minute), or if you are trying to create such a class, say for educational interest,
- Follow the "rule of 5" (used to be 3, before C++11 introduced move semantics). Whenever you have a data member that needs some special creation/destruction, make sure you deal with it appropriately in all constructors and destructors: copy/move construction/assignment, and destruction.
Note that at the moment, it is impossible to properly write a copy constructor/assignment operator, since you don't store the size of the array, so you don't know what size the copy should be.
For instance, if you store the array size in an int
member named i
, your copy constructor might look like:
MyClass(const MyClass& rhs) : a(0), i(rhs.i) {
a = new int[i];
std::copy(rhs.a, rhs.a+rhs.i, a);
}
Writing a copy assignment operator is a bit trickier, since you need to deal with delete
ing the existing array, and even with restoring the original state if allocating the new array throws an exception:
Edit: sorry, my previous operator=
example was total crap, this version is better:
MyClass& operator=(const MyClass& rhs) {
int *newA = new int[rhs.i];
std::copy(rhs.a, rhs.a+rhs.i, newA);
i = rhs.i;
delete[] a;
a = newA;
return *this;
}
You only replace the existing member after building the new one. This way, if allocating the new one throws an exception, the object is still in its old state.