M90 M90 - 1 month ago 12
C++ Question

c++ operator new how this works internally

For example I have a simple code:

class B
{
};

class A
{
B b;
public:
A()
{
throw 1;
}
};

int main()
{
A* a = 0;
try
{
a = new A;
}
catch (int)
{
}
}


Constructor A throws exception, then destructor will not be called. But destructor for B will be called. Memory in the heap will not be allocated. My question how this works internally? What will be first: constructing A or allocating memory in the heap? So, if allocating is the first, how deallocating will be handled if there are exception? Othervise, if constructing A is the first, how it's copiing to the heap?

Answer
  1. The memory is allocated.
  2. The constructor of A is called.
  3. The constructor of A calls the constructor of B.
  4. The constructor of A throws.
  5. As a part of the standard exception handling procedure, the destructor of B is called (RAII at work).
  6. The stack unwinds to the caller (main).
  7. The memory is deallocated (because the object wasn't constructed successfully).

The destructor of A isn't called because the object was not fully constructed. However, the members which were fully constructed are still destroyed.

The memory is deallocated automatically in pretty much the same way as local variables are destroyed when the control leaves the block. If you're familiar with Java and/or C#, think of it as an invisible try-finally construct. Or a series of such constructs.