The c++ programming language by Bjarne Stroustrup - operator new

Viewed 159

Section "11.2.4 Overloading new" ends with:

"There is no special syntax for placement of arrays. Nor need there be since arbitrary types can be allocated by placement new. However, an operator delete can be defined for arrays".

If I understand it correctly, what is being said is that for arrays, we use the usual placement new syntax, which would invoke the appropriate operator new[]. But, what I don't understand is the last sentence. What is he trying to say there? Afaik, we can specify both operator new and operator delete for arrays.

1 Answers

There is a special allocator for arrays (operator new[]()) but it is not dependent on a special syntax.

In the following code

new T();

or

new (p) T();

The compiler will generate a call to either operator new(...) or operator new[](...) depending on whether T is an array type. There is no syntactic difference in the new-expression.

(Now, there is a special syntax for a new-expression with a runtime size... but invocation of operator new[]() is not limited to scenarios with a runtime size)


In contrast to new, for delete the same pointer type is compatible with both scalar and array. So you the programmer must tell the compiler which you want via

delete p;

vs

delete [] p;

There is no automatic translation to delete[] based on recognition of an array type.

Related