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?
No. If an exception occurs during the Fred constructor of p = new Fred(), the C++ language guarantees that the memory sizeof(Fred) bytes that were allocated will automagically be released back to the heap.
A constructor does not allocate memory for the class object its this pointer refers to, but may allocate storage for more objects than its class object refers to. If memory allocation is required for objects, constructors can explicitly call the new operator.
When new is used to allocate memory for a C++ class object, the object's constructor is called after the memory is allocated. Use the delete operator to deallocate the memory allocated by the new operator.
In the above example, if new fails to allocate memory, it will return a null pointer instead of the address of the allocated memory. Note that if you then attempt indirection through this pointer, undefined behavior will result (most likely, your program will crash).
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With