Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How operator new calls the constructor of class?

Tags:

c++

I know that, new operator will call the constructor of class.

But how it's happening, what is ground level techniques used for this.

like image 825
Ganesh Kumar Avatar asked May 31 '10 07:05

Ganesh Kumar


2 Answers

Here is how I imagine it:

T* the_new_operator(args)
{
    void* memory = operator new(sizeof(T));
    T* object;
    try
    {
        object = new(memory) T(args);   // (*)
    }
    catch (...)
    {
        operator delete(memory);
        throw;
    }
    return object;
}

(*) Technically, it's not really calling placement-new, but as long as you don't overload that, the mental model works fine :)

like image 159
fredoverflow Avatar answered Nov 02 '22 02:11

fredoverflow


It's not really the new operator that calls the constructor. It is more the compiler that translate the following line:

MyClass * mine = new MyClass();

Into the following:

MyClass * mine = malloc(sizeof(MyClass));  // Allocates memory
mine->MyClass();                           // Calls constructor

With other error handling code that other answers have noted.

like image 35
Didier Trosset Avatar answered Nov 02 '22 01:11

Didier Trosset