why call operator new explicitly
I saw code like this:
void *NewElts = operator new(NewCapacityInBytes);
And matching call explicitly operator delete
is used consequent later.
Why do this instead of:
void *NewElts = new char[NewCapacityInBytes];
Why explicit cal开发者_如何学JAVAl to operator new
and operator delete
??
Explicitly calling operator new
like that calls the global "raw" operator new. Global operator new
returns a raw memory block without calling the object's constructor or any user-defined overloads of new
. So basically, global operator new
is similar to malloc
from C.
So:
// Allocates space for a T, and calls T's constructor,
// or calls a user-defined overload of new.
//
T* v = new T;
// Allocates space for N instances of T, and calls T's
// constructor on each, or calls a user-defined overload
// of new[]
//
T* v = new T[N];
// Simply returns a raw byte array of `sizeof(T)` bytes.
// No constructor is invoked.
//
void* v = ::operator new(sizeof(T));
If you write:
T *p = new T;
That allocates enough memory to hold a T, then constructs the T into it. If you write:
T *p = ::operator new(sizeof(T));
That allocates enough memory to hold a T, but doesn't construct the T. One of the times you might see this is when people are also using placement new:
T *p = ::operator new(sizeof(T)); // allocate memory for a T
new (p) T; // construct a T into the allocated memory
p->~T(); // destroy the T again
::operator delete(p); // deallocate the memory
If you call operator new(bytesize), then you can delete it using delete, whereas if you allocate via new char[bytesize], then you have to match it using delete[], which is an abomination to be avoided wherever possible. This is most likely the root reason to use it.
Use it when you want to allocate a block of "raw" memory and don't want anything constructed in that memory.
There is little practical difference between allocating a block of raw memory and "constructing" an array of chars but using operator new clearly signals your intent to anyone reading the code which is important.
精彩评论