To understand what this function does, I think it is necessary to take a look at what a new-expression does: It calls an allocation function to obtain storage for the object, then it constructs that object in the memory region the allocation function indicated (by returning a pointer to said memory region).
This implies that construction is never performed by the allocation function itself. The allocation function has the strange name operator new
.
It is possible to supply additional parameters for the allocation function by using the placement-new syntax:
new int(5) // non-placement form
new(1,2,3) int(5) // placement-form
However, placement-new typically refers to a very specific new-expression:
void* address = ...;
::new(address) int(5) // "the" placement-form
This form is intended to construct an object in an already allocated region of memory, i.e. it is intended to just call the constructor, but not perform any allocation.
No special case has been introduced in the core language for that case. Rather, a special allocation function has been added to the Standard Library:
void* operator new (std::size_t size, void* ptr) noexcept;
Being a no-op (return ptr;
), it allows calling the constructor for an object explicitly, constructing at a given memory location. This function call can be eliminated by the compiler, so no overhead is introduced.
*ptr
. It is simply called by a new-expression, which always calls an allocation function - and this one is the no allocation function. Construction of the object is performed by the compiler evaluating the new-expression (outside of the call to this function). – Garrottoperator new
function. It is called by the compiler after completion of this function, as a part of evaluating the new-expression. – Garrottoperator new
function and then calls a constructor. In the placement new case that uses thisoperator new
,operator new
itself does absolutely nothing and cannot fail, but the new-expression can still be undefined behavior. – Padrone