std :: aligned_storage如何为任何对象公开正确对齐的存储? [英] How can std::aligned_storage expose correctly aligned storage for any object?
问题描述
std::aligned_storage
结构提供了至少根据 cppreference的type
typedef :
The std::aligned_storage
structure provides a type
typedef that at least according to cppreference:
提供成员typedef类型,它是适合使用的PODType 对于任何大小最大为Len和的对象,作为未初始化的存储 其对齐要求是Align的除数.
Provides the member typedef type, which is a PODType suitable for use as uninitialized storage for any object whose size is at most Len and whose alignment requirement is a divisor of Align.
Align的默认值是最严格的(最大) 任何尺寸最大为Len的物体的对齐要求.
The default value of Align is the most stringent (the largest) alignment requirement for any object whose size is at most Len.
尤其是,默认值为Align
,适用于大小小于或等于Len的任何对象.
In particular, with the default value of Align
, the suitably aligned for any object whose size is at most Len.
请注意,对于过度对齐的类型(在我使用的平台gcc,至少支持某些过度对齐的类型)没有任何警告或例外.
Note that there are no caveats or exceptions for over-aligned types (and in any case the platform I'm using, gcc, supports at least some over-aligned types).
这样的实现实际上如何工作?为了满足任何对象"的要求,似乎可以:
How can such an implementation actually work? To satisfy the requirement of "any object" it would seem that it would either:
- 在类型为
T
的alignof(T) <= sizeof(T)
的平台上,必须始终对齐到大致Len
个字节,因为大小为Len
的对象可能具有最大为Len
的对齐方式.当然,这对于大型Len
会浪费很多内存! - 在
alignof(T)
可能大于sizeof(T)
的平台上,我完全不知道如何实现.但是,不清楚我,甚至可以存在这种类型.
- On a platform where
alignof(T) <= sizeof(T)
for typesT
, need to always align to roughlyLen
bytes, since an object of sizeLen
could have an alignment of up toLen
. Of course, this would waste a lot of memory for largeLen
! - On a platform where
alignof(T)
may be larger than thansizeof(T)
, I don't see how it could be implemented at all. However, it isn't clear to me that such a type can even exist.
基于我的测试,用于默认Align
值,gcc
始终总是与16对齐,而与len无关.这意味着存储不不适合任何对象,而仅适用于基本对齐的对象(在此平台上为alignof(max_align_t) == 16
).
Based on my testing, for default Align
values, gcc
simply always aligns to 16, regardless of len. This means the storage is not suitable for any object, but only objects of fundamental alignment (alignof(max_align_t) == 16
on this platform).