Search code examples
c++boostc++17boost-optionalstdoptional

Do std::optional and boost::optional respect alignment restrictions of the managed object?


If a class T has an alignment requirement, such as one specified by the alignas keyword, are std::optional<T> and boost::optional<T> guaranteed to respect said alignment?

If they were simply wrapper classes for a T object and a bool initialized, then they would automatically align their T member as required, but the standard and boost documentation state that they can hold no object and deal well with expensive to construct objects. From this I understand that they don't simply contain a T. Rather, they seem to allocate a buffer upon which the T is constructed or destroyed manually. Therefore, the C++ language will not automatically align the buffer because it is not of type T.

So, do std::optional<T> and boost::optional<T> properly align their managed T object? Do they also provide optional<T>::operator new and optional<T>::operator new[] that respect the alignment requirement?


Solution

  • A conforming implementation of std::optional must respect the alignment requirements of its value_type according to the C++17 standard draft:

    23.6.3 Class template optional [optional.optional]

    (...) The contained value shall be allocated in a region of the optional storage suitably aligned for the type T.

    An implementor could use a union potentially containing the value as member, ensuring proper alignment.

    As Thomas already mentioned while I was looking it up, boost::optional does ensure proper alignment by use of aligned_storage<T>