开发者

How operator new calls the constructor of class?

开发者 https://www.devze.com 2023-01-01 09:08 出处:网络
I know that, new operator will call t开发者_JAVA百科he constructor of class. But how it\'s happening, what is ground level techniques used for this.Here is how I imagine it:

I know that, new operator will call t开发者_JAVA百科he constructor of class.

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


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


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.


The compiler generates machine code for that. When the compiler sees

CSomeClass* object = new CSomeClass();

(new statement) it generates code that calls the appropriate operator new() (which allocates memory), calls the right constructor, calls destructors of all fully constructed subobjects in case of exception, calls operator delete() in case an exception occurs during construction. All this is done by extra machine code generated by the C++ compiler for that simply looking statement.

0

精彩评论

暂无评论...
验证码 换一张
取 消