Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
248 views
in Technique[技术] by (71.8m points)

c++ - What are "::operator new" and "::operator delete"?

I know new and delete are keywords.

int obj = new int;
delete obj;

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

<new> header is a part of C++ standard headers. It has two operators (I am not sure they are operators or they are functions):

::operator new

::operator delete

these operators used like below:

#include <new>
using namespace std;

int* buff = (int*)::operator new(1024 * sizeof(int));
::operator delete(buff);

What are "::operator new" and "::operator delete"? Are they different from new and delete keywords?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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<Object*>(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<Object*>(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*).


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...