Reputation: 835
I have a constructor that allocates several blocks of memory using the new
operator.
X::X() {
a = new int[100];
b = new char[100];
c = new float[100];
}
My question is, if the allocation of c
fails, and the constructor throws an exception, will the memory for a
and b
be automatically freed?
Upvotes: 12
Views: 1444
Reputation: 234875
The memory to which a
and b
point would not be automatically freed. Every new[]
must be balanced explicitly with a delete[]
.
Even if your destructor performed the deletion (assuming a
, b
, and c
are class members), then you'd still leak memory. That's because the destructor wouldn't be called in this case since the object failed to construct.
Using std::vector
s would obviate these problems.
Upvotes: 14
Reputation: 76523
a
, b
, and c
will all be destroyed. Depending on what types they are, that might or might not release the memory. If they are pointers their destructors don't do anything, and the memory leaks. If they are some sort of smart pointer, presumably their destructors will release the memory.
Upvotes: 9
Reputation: 19
Variable a and b will not be automatically destroyed for sure. In your case you must use this std::vector. This is because whenever we use a new[] operator for that we need to explicitly define a delete[].
Upvotes: 1