5

I'm a bit confused about the alignement requirements when std::aligned_storage is used and dynamic allocation is needed. Example:

  using storage = typename std::aligned_storage<sizeof(T), std::alignment_of<T>::value>::type;
  storage* pool;
  pool = ::new storage[num_obj];

Is it legal? The new operator doesn't return alignment memory, so is the result correct?

0

1 Answer 1

4

The C++11 standard requires that allocation functions such as ::operator new return memory that is aligned to alignof(std::max_align_t) [basic.stc.dynamic/2]:

The pointer returned shall be suitably aligned so that it can be converted to a pointer of any complete object type with a fundamental alignment requirement […]

Thus, as long as the type of the object you're creating via your new expression is not an overaligned type (one that requires an alignment more strict than alignof(std::max_align_t)), everything's fine. For overaligned types, you would indeed have to allocate storage of sufficient size to manually align the pointer, e.g., using std::align, and then construct your object at a suitable address, e.g., via placement new…

Starting with C++17, new automatically takes care of this. To allocate storage that requires alignment more strict than __STDCPP_­DEFAULT_­NEW_­ALIGNMENT__ (the alignment that allocation functions are at least required to supply), a new-expression will call an allocation function that is explicitly given the alignment of the storage to be allocated as an argument [expr.new]/14

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.