Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

c++ non fully constructed object deallocation

Tags:

c++

exception

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 ).

like image 563
AlexDan Avatar asked Jul 15 '26 01:07

AlexDan


1 Answers

The allocation done by new A() consists of multiple steps:

  1. Allocate memory using operator new(sizeof(A)).
  2. Try to default construct an object in the allocated memory.
  3. When default construction fails, 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 calls operator new(size_t, Alloctor) (where allocator is convertible to Allocator), a corresponding operator 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.

like image 72
Dietmar Kühl Avatar answered Jul 17 '26 14:07

Dietmar Kühl