Code :
#include<iostream>
using namespace std;
class A{
public:
A(){cout << "A() Constructor " << endl;
throw 1;
}
};
int main(){
A* p=0;
cout << p << endl; // p value is 0
try{
p=new A(); // object is not fully constructed, no address is returned to p. for future deallocation
}
catch(...){cout << "Exception" << endl;}
cout << p << endl; // this will output that p has the value 0,proof that no address was returned to p.
}
memory is allocated for A object in the heap, the address of the memory is passed to the constructor
but when the constructor throw 1; then object of type A will not considered to be a fully constructed object. so no
pointer will be returned the pointer p. feel free to correct me if I’ve understood something wrong.
Questions:
1) So my question is how it is possible in such case to deallocate memory for the A object. Im not talking about
The destructor call, but the deallocation of memory.
2) what about when I create a local object of type A inside main function. and obviously it wont be fully constructed either. when does this object get deallocated (ofcourse after calling the destructor of fully construted subobjects ).
The allocation done by
new A()consists of multiple steps:operator new(sizeof(A)).operator delete(x)is called with the address obtained earlier.More generally, if you use an overloaded
operator new(), e.g.,new(allocator) A()which callsoperator new(size_t, Alloctor)(whereallocatoris convertible toAllocator), a correspondingoperator delete()is called.As part of exception throwing, all partially constructed subobjects are destroyed (in the reverse order in which they were constructed) as well. That is, if an exception is thrown from the constructor of an object, you don’t need to care about clean-up (assuming, all subobjects correctly look after the resources they have allocated). This is true independent on whether the object is allocated on the heap or the stack.