Looks like operator new
and operator new[]
have exactly the same signature:
void* operator new( size_t size );
void* operator new[]( size_t size );
and do exactly the same: either return a pointer to a big enough block of raw (not initialized in any way) memory or throw an exception.
Also operator new
is called internally when I create an object with new
and operator new[]
- when I create an array of objects with new[]
. Still the above two special functions are called by C++ internally in exactly the same manner and I don't see how the two calls can have different meanings.
What's the purpose of having two different functions with exactly the same signatures and exactly the same behavior?
The new operator lets developers create an instance of a user-defined object type or of one of the built-in object types that has a constructor function.
new operator. The new operator denotes a request for memory allocation on the Free Store. If sufficient memory is available, a new operator initializes the memory and returns the address of the newly allocated and initialized memory to the pointer variable.
There's no difference between "new operator" and "operator new". Both refer to the same thing: the overloadable/replaceable operator new function that typically performs raw memory allocation for objects created by new-expressions.
The delete operator removes a given property from an object. On successful deletion, it will return true , else false will be returned.
The operators can be overridden (for a specific class, or within a namespace, or globally), and this allows you to provide separate versions if you want to treat object allocations differently from array allocations. For example, you might want to allocate from different memory pools.
I've had a reasonably good look at this, and to be blunt there's no reason from an interface standpoint.
The only possible reason that I can think of is to allow an optimization hint for the implementation, operator new[]
is likely to be called upon to allocate larger blocks of memory; but that is a really, really tenuous supposition as you could new
a very large structure or new char[2]
which doesn't really count as large.
Note that operator new[]
doesn't add any magic extra storage for the array count or anything. It is the job of the new[]
operator to work out how much overhead (if any) is needed and to pass the correct byte count to operator new[]
.
[A test with gcc indicates that no extra storage is needed by new[]
unless the type of the array members being constructed have a non-trivial desctructor.]
From an interface and contract standpoint (other than require the use of the correct corresponding deallocation function) operator new
and operator new[]
are identical.
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