M90
M90

Reputation: 49

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?

Upvotes: 1

Views: 188

Answers (2)

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 727137

What will be first: constructing A or allocating memory in the heap?

Unless there's memory, there's no space in which the object can be constructed. Memory allocation always goes first; then the code proceeds with initialization. This applies to all kinds of memory allocations, not only of the dynamic variety, because constructors need to have a valid address of this before they start initializing the object.

If allocating is the first, how deallocating will be handled if there are exception?

The compiler emits special code that handles the "magic" here. This code will run destructors for all base classes, and for members, such as B, that have been fully constructed by the time the code entered A's constructor.

Upvotes: 0

Sergei Tachenov
Sergei Tachenov

Reputation: 24919

  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.

Upvotes: 4

Related Questions