Andrew Tomazos Andrew Tomazos - 1 year ago 127
C++ Question

Placement new in std::aligned_storage?

Suppose I have a type template parameter T.

And suppose I have a

as follows:

typename std::aligned_storage<sizeof(T), alignof(T)>::type storage;

I want to placement new a T into the

What is the standard-compliant pointer value/type to pass to the placement new operator, and how do I derive that from

new (& ???) T(a,b,c);

For example:

new (&storage) T(a,b,c);
new (static_cast<void*>(&storage)) T(a,b,c);
new (reinterpret_cast<T*>(&storage)) T(a,b,c);
new (static_cast<T*>(static_cast<void*>(&storage));

Which of the above (if any) are compliant, and if none, what is the better way?

Answer Source

The most paranoid way is

::new ((void *)::std::addressof(storage)) T(a, b, c);


  • ::std::addressof guards against overloaded unary operator& on storage, which is technically allowed by the standard. (Though no sane implementation would do it.) The ::std guards against any non-top-level namespaces (or classes) called std that might be in scope.
  • (void *) (which in this case is a static_cast) ensures that you call the placement operator new taking a void * rather than something else like decltype(storage) *.
  • ::new skips any class-specific placement operator news, ensuring that the call goes to the global one.

Together, this guarantees that the call goes to the library placement operator new taking a void *, and that the T is constructed at where storage is.

In most sane programs, though,

new (&storage) T(a,b,c);

should be sufficient.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download