In his new book TC++PL4, Stroustrup casts a slightly different light on a once usual practice regarding user-controlled memory allocation and placement new
—or, more specifically, regarding the enigmatical "placement delete
." In the book's sect. 11.2.4, Stroustrup writes:
The "placement
delete
" operators do nothing except possibly inform a garbage collector that the deleted pointer is no longer safely derived.
This implies that sound programming practice will follow an explicit call to a destructor by a call to placement delete
.
Fair enough. However, is there no better syntax to call placement delete
than the obscure
::operator delete(p);
The reason I ask is that Stroustrup's sect. 11.2.4 mentions no such odd syntax. Indeed, Stroustrup does not dwell on the matter; he mentions no syntax at all. I vaguely dislike the look of ::operator
, which interjects the matter of namespace resolution into something that properly has nothing especially to do with namespaces. Does no more elegant syntax exist?
For reference, here is Stroustrup's quote in fuller context:
By default, operator
new
creates its object on the free store. What if we wanted the object allocated elsewhere?... We can place objects anywhere by providing an allocator function with extra arguments and then supplying such extra arguments when usingnew
:void* operator new(size_t, void* p) { return p; } void buf = reinterpret_cast<void*>(0xF00F); X* p2 = new(buf) X;
Because of this usage, the
new(buf) X
syntax for supplying extra arguments tooperator new()
is known as the placement syntax. Note that everyoperator new()
takes a size as its first argument and that the size of the object allocated is implicitly supplied. Theoperator new()
used by thenew
operator is chosen by the usual argument-matching rules; everyoperator new()
has asize_t
as its first argument.The "placement"
operator new()
is the simplest such allocator. It is defined in the standard header<new>
:void* operator new (size_t, void* p) noexcept; void* operator new[](size_t, void* p) noexcept; void* operator delete (void* p, void*) noexcept; // if (p) make *p invalid void* operator delete[](void* p, void*) noexcept;
The "placement
delete
" operators do nothing except possibly inform a garbage collector that the deleted pointer is no longer safely derived.
Stroustrup then continues to discuss the use of placement new
with arenas. He does not seem to mention placement delete
again.