45. Always provide new
and delete
together
Summary
They’re a package deal: Every class-specific overload void* operator new(
parms
)
must be accompanied by a corresponding overload void operator delete(void*,
parms
)
, where parms
is a list of extra parameter types (of which the first is always std::size_t
). The same goes for the array forms new[]
and delete[]
.
Discussion
You rarely need to provide a custom new
or delete
, but if you need one you usually need both. If you define a class-specific T::operator new
to do some special allocation, it’s very likely you need to define a class-specific T::operator delete
as well to do the corresponding special deallocation.
That much may be somewhat basic, but there is a subtler reason for this Item: The ...
Get C++ Coding Standards: 101 Rules, Guidelines, and Best Practices now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.