Should i deallocate dynamic array (allocated in constructor) in copy constructor and/or assignment operator?
struct Test
{
const size_t n;
int* xs;
Test(const size_t n)
: n(n)
, xs(new int[n])
{ }
Test(const Test& other)
: n(other.n)
, xs(new int[n])
{
memcpy(xs, other.xs, n * sizeof(int));
}
Test& operator=(const Test& other)
{
n = other.n;
delete[] xs;
xs = new int[n];
memcpy(xs, other.xs, n * sizeof(int));
}
~Test()
{
delete[] xs;
}
};
void main()
{
Test a(10);
Test b(a);
Test c(20);
c = b;
}
As you can see, I guess that you have to delete[]
the array in assignment operator implementation (since it has been already allocated somewhere during construction of the object that's being assigned to). And I do think that you don't need to deallocate the array while copy constructing the object, since it has not been constructed yet.
The thing is, running the application above under Application Verifier shows no memory leaks no matter if there is delete[]
in operator=
or if there is not. Application runs OK though in both cases.
So, should I delete[] xs
in copy constructor, assignment operator, both or neither?
Test& operator=(const Test& other) : n(other.n)
compiled? And yes, you should. – Luchian Grigorenew[]
anddelete[]
at all. Use astd::vector
. – jamesdlinstd::vector
and it turned out to be awfully slow. – Egor Tensin