What are “::operator new” and “::operator delete”?

后端 未结 4 1061
我在风中等你
我在风中等你 2020-12-18 05:01

I know new and delete are keywords.

int obj = new int;
delete obj;

int* arr = new int[1024];
delete[] arr;

4条回答
  •  天涯浪人
    2020-12-18 05:23

    the new keyword (used alone) is not the same as the operator new function.

    Calling

    Object* p = new Object(value);
    

    is equvalent in calling

    void* v = operator new(sizeof(Object));
    p = reinterpret_cast(v);
    p->Object::Object(value); //this is not legal C++, it just represent the implementation effect
    

    The operator new (or better the void* operator new(size_t) variant) just allocate memory, but does not do any object construction.

    The new keyword calls the operator new function, but then calls the object constructor.

    To separate allocation from contruction, a variant of operator new is declared as

    void* operator new(size_t, void* at)
    { return at; }
    

    and the previous code is typically written as

    Object* p = reinterpret_cast(operator new(sizeof(Object))); //no contruction here
    new(p) Object(value); //calls operator new(size_t, void*) via keyword
    

    The operator new(size_t, void*) does nothing in itself, but, being invoked by the keyword will result in the contructor being called.

    Reversely, destruction and deallocation can be separated with

    p->~Object();
    operator delete(p); //no destructor called
    

    instead of delete p; that calls the destructor and then operator delete(void*).

提交回复
热议问题