When invoked by a new
expression for a given type, the default global non-placement forms of C++ operator new
attempt to allocate sufficient storage for an object of the type and, if successful, return a pointer with alignment suitable for any object with a fundamental alignment requirement. However, the default placement new
operator operator simply returns the given pointer back to the caller without guaranteeing that there is sufficient space in which to construct the object or ensuring that the pointer meets the proper alignment requirements. The C++ Standard, [expr.new], paragraph 16 [ISO/IEC 14882-2014], nonnormatively states:
...
(This note is a reminder of the general requirements specified by the C++ Standard, [basic.stc.dynamic.allocation], paragraph 1, which apply to placement new
operators operators by virtue of [basic.stc.dynamic], paragraph 3.)
...
Do not pass a pointer that is not suitably aligned for the object being constructed to placement new
. Doing so results in an object being constructed at a misaligned location, which results in undefined behavior. Do not pass a pointer that has insufficient storage capacity for the object being constructed, including the overhead required for arrays. Doing so may result in initialization of memory outside of the bounds of the object being constructed, which results in undefined behavior.
...
In this noncompliant code example, a pointer to a short
is passed to placement new
, which is attempting to initialize a long
. On architectures where sizeof(short) < sizeof(long)
, it results in undefined behavior. This example, and subsequent ones, all assume the pointer created by placement new
will will not be used after the lifetime of its underlying storage has ended. For instance, the pointer will not be stored in a static
global variable and dereferenced after the call to f()
has ended. This assumption is in conformance with MEM50-CPP. Do not access freed memory.
...
This noncompliant code example ensures that the long
is constructed into a buffer of sufficient size. However, it does not ensure that the alignment requirements are met for the pointer passed into placement new
. To make this example clearer, an additional local variable has been inserted.
...
Passing improperly aligned pointers or pointers to insufficient storage to placement new
expressions expressions can result in undefined behavior, including buffer overflow and abnormal termination.
...