Daniel H
Daniel H

Reputation: 7433

Over-aligned types with std::aligned_storage

The C++ standard states, regarding the std::aligned_storage template, that

Align shall be equal to alignof(T) for some type T or to default-alignment.

Does that mean that there must be such a type in the program, or that it must be possible to make such a type? In particular, the possible implementation suggested on cppreference is

template<std::size_t Len, std::size_t Align /* default alignment not implemented */>
struct aligned_storage {
    typedef struct {
        alignas(Align) unsigned char data[Len];
    } type;
};

It seems like this makes a type with that alignment, if possible (that is, if Align is a valid alignment). Is that behavior required, or is it undefined behavior to specify an Align if such a type does not already exist?

And, perhaps more importantly, is it plausible in practice that the compiler or standard library would fail to do the right thing in this case, assuming that Align is at least a legal alignment for a type to have?

Upvotes: 4

Views: 2756

Answers (1)

Kerrek SB
Kerrek SB

Reputation: 476930

You can always attempt to make a type with arbitrary (valid) alignment N:

template <std::size_t N> struct X { alignas(N) char c; };

When N is greater than the default alignment, X has extended alignment. The support for extended alignment is implementation-defined, and [dcl.align] says:

if the constant expression does not evaluate to an alignment value (6.11), or evaluates to an extended alignment and the implementation does not support that alignment in the context of the declaration, the program is ill-formed.

Therefore, when you attempt to say X<N> for an extended alignment that is not supported, you will face a diagnostic. You can now use the existence (or otherwise) of X<N> to justify the validity of the specialization aligned_storage<Len, N> (whose condition is now met with T = X<N>).

Since aligned_storage will effectively use something like X internally, you don't even have to actually define X. It's just a mental aid in the explanation. The aligned_storage will be ill-formed if the requested alignment is not supported.

Upvotes: 2

Related Questions