C++ Memory Management – Purpose of Separate Operator New[]

c++memory-management

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?

Best Answer

In Design and Evolution of C++ (section 10.3), Stroustrup mentions that if the new operator for object X was itself used for allocating an array of object X, then the writer of X::operator new() would have to deal with array allocation too, which is not the common usage for new() and add complexity. So, it was not considered to use new() for array allocation. Then, there was no easy way to allocate different storage areas for dynamic arrays. The solution was to provide separate allocator and deallocator methods for arrays: new[] and delete[].