I am having a potentially unstable class that someone else wrote, and I'm having to create an array of objects of that class. I mentioned that the class is unstable, so it may occasionally throw an exception in the default constructor. I don't have access to the source code, only the compiled binaries.
When I am allocating the dynamic array of these type of objects using new
, there is the chance that one of these bad objects may throw an exception. It is throwing a custom exception, not std::bad_alloc
.
Anyway, I need to make the program recover from the exception and just keep on chugging, albeit setting some error flags and what not. I think that I should delete
the memory associated with the array to prevent a memory leak.
My reasoning is that if the class throws an exception constructing an element somewhere in the middle of the array, that element won't be constructed properly, and all the future elements will be stopped constructing by the exception, but the previous elements will have been properly constructed since that happened before the exception was thrown. I am wondering, is it a good idea to call delete
in the catch (...) { }
? How would I go about solving this memory leak?
Badclass* array = nullptr;
try {
array = new Badclass[10]; // May throw exceptions!
} catch (...) {
delete[] array;
array = nullptr;
// set error flags
}
This is the way I visualize this in the memory. Is this correct?
array 0 1 2 3 4 5 6 7 8 9
___ __________________________________
| ---------->| :) | :) | :) | :) | :( | | | | | |
|___| |____|____|____|____|____|_|_|_|_|_|