Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 call to operator new and operator delete??

like image 267
zaharpopov Avatar asked Nov 10 '10 14:11

zaharpopov


People also ask

Why new is an operator in C++?

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.

What is the difference between new operator and operator new?

Operator vs function: new is an operator as well as a keyword whereas operator new is only a function.

How do you call a new operator in C++?

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.

What happens when you call new C++?

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 ...


1 Answers

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));
like image 194
Charles Salvia Avatar answered Oct 07 '22 23:10

Charles Salvia