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

后端 未结 4 1070
我在风中等你
我在风中等你 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:39

    They are allocator and deallocator functions. The new operator does two things: it calls an allocator function to get the memory, and it calls the constructor of the object. The delete operator also does two things: it calls the destructor, and then calls the a deallocator function. The default allocator function is ::operator new, and the default deallocator function is ::operator delete. Both can be replaced by the user.

    Note that in a new expression, the ::operator new function is looked up in more or less the same manner as it would be if it were a normal function called from within a member function. As for normal functions, you can qualify the operator to change the lookup: new MyClass will find a member operator new if one is present; ::new MyClass will use the default allocator, even if MyClass defines a member operator new.

提交回复
热议问题