If I do:
MyClass * p = new MyClass;
And an exception is thrown by the constructor of MyClass, do I need to do:
delete p
In order to free the memory? I have read that the in that case the destructor is not called, but I need to know whether the memory is automatically freed immediately after the exception.
I have the same question in a more complicated case:
Suppose I do:
MyClass ** p = new MyClass[100];
And only the constructor of the single MyClass object #73 throws an exception.
What happens? Will the destructor of the other 99 objects will ever happen? Will my app somehow remember that object number 73 in that array should not be handled by it's destructor?
Or maybe all of those 100 objects will never be handled by a destactor? In that case do I need to do:
delete [] p;
Or is it done automatically immediately after the exception is thrown?
Question 1: No; an object that is dynamically allocated and fails to construct does not need to be freed. You couldn't free it anyway since delete always runs destructors.
Question 2: you have a syntax error; I assume you meant MyClass* p = new MyClass[ 100 ];. If object #73 throws in its constructor, then the C++ standard guarantees you that the destructors for objects 1-72 are run prior to catching the exception, and that the destructor for #73 is not called. Furthermore, as in the first question, it is as if you never allocated any memory at all; the pointer does not need to be freed, as using array delete would again attempt to run destructors on objects that were already destroyed or never constructed in the first place.