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 call to operator new
and operator delete
??
Use of the new operator signifies a request for the memory allocation on the heap. If the sufficient memory is available, it initializes the memory and returns its address to the pointer variable. The new operator should only be used if the data object should remain in memory until delete is called.
Operator vs function: new is an operator as well as a keyword whereas operator new is only a function.
When new is used to allocate memory for a C++ class object, the object's constructor is called after the memory is allocated. Use the delete operator to deallocate the memory allocated by the new operator. Use the delete[] operator to delete an array allocated by the new operator.
operator new can be called explicitly as a regular function, but in C++, new is an operator with a very specific behavior: An expression with the new operator, first calls function operator new (i.e., this function) with the size of its type specifier as first argument, and if this is successful, it then automatically ...
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 love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With