c – 使用std :: aligned_storage的过度对齐类型

关于std :: aligned_storage模板,C标准说明了这一点

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

这是否意味着程序中必须存在这样的类型,或者必须能够制作这样的类型?特别是,关于cppreference的possible implementation建议是

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;
};

如果可能的话(例如,如果Align是有效对齐),似乎这会使具有该对齐的类型.是否需要该行为,或者如果此类型尚不存在,则指定Align是否为未定义行为?

并且,或许更重要的是,在实践中,编译器或标准库在这种情况下无法做正确的事情是合理的,假设Align至少是一个类型的合法对齐方式?

最佳答案 您始终可以尝试使用任意(有效)对齐N来创建类型:

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

当N大于默认对齐时,X已扩展对齐.对扩展对齐的支持是实现定义的,[dcl.align]说:

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.

因此,当您试图说X< N>时对于不受支持的扩展对齐,您将面临诊断.您现在可以使用X< N>的存在(或其他).为了证明专业化的有效性,align_storage< Len,N> (其条件现在满足T = X< N>).

由于aligned_storage会在内部有效地使用类似X的东西,你甚至不必实际定义X.这只是解释中的心理辅助.如果不支持请求的对齐,对齐的存储将是格式错误的.

点赞