How operator new calls the constructor of class?

前端 未结 3 411
Happy的楠姐
Happy的楠姐 2021-01-13 09:45

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

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

3条回答
  •  一向
    一向 (楼主)
    2021-01-13 10:13

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

提交回复
热议问题