std::aligned_storage 的过度对齐类型
Over-aligned types with std::aligned_storage
C++ 标准规定,关于 std::aligned_storage
模板,
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>
的存在(或其他)来证明专业化 aligned_storage<Len, N>
的有效性(其条件现在满足 T = X<N>
)。
由于 aligned_storage
将有效地在内部使用类似 X
的东西,您甚至不必实际定义 X
。这只是解释中的精神帮助。如果不支持请求的对齐方式,aligned_storage
将格式错误。
C++ 标准规定,关于 std::aligned_storage
模板,
Align
shall be equal toalignof(T)
for some typeT
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>
的存在(或其他)来证明专业化 aligned_storage<Len, N>
的有效性(其条件现在满足 T = X<N>
)。
由于 aligned_storage
将有效地在内部使用类似 X
的东西,您甚至不必实际定义 X
。这只是解释中的精神帮助。如果不支持请求的对齐方式,aligned_storage
将格式错误。