不,它不。该结构将填充到所请求的对齐方式,但不会对齐。然而,有一个机会,这将是allowed in C++17(事实上,这个C++ 17建议存在应该是非常好的证明,这不能在C++ 11中工作)。
我看到这似乎与一些内存分配器,但这是纯粹的运气。例如,某些内存分配器会将其内存分配与所需大小(最大4KB)的2次幂对齐,作为分配器的优化(减少内存碎片,可能使重新使用先前释放的内存变得更容易,等等) 。但是,我测试的OS X 10.7和CentOS 6系统中包含的新/ malloc实现不会执行此操作,并会失败,并显示以下代码:
#include
#include
struct alignas(8) test_struct_8 { char data; };
struct alignas(16) test_struct_16 { char data; };
struct alignas(32) test_struct_32 { char data; };
struct alignas(64) test_struct_64 { char data; };
struct alignas(128) test_struct_128 { char data; };
struct alignas(256) test_struct_256 { char data; };
struct alignas(512) test_struct_512 { char data; };
int main() {
test_struct_8 *heap_8 = new test_struct_8;
test_struct_16 *heap_16 = new test_struct_16;
test_struct_32 *heap_32 = new test_struct_32;
test_struct_64 *heap_64 = new test_struct_64;
test_struct_128 *heap_128 = new test_struct_128;
test_struct_256 *heap_256 = new test_struct_256;
test_struct_512 *heap_512 = new test_struct_512;
#define IS_ALIGNED(addr,size) ((((size_t)(addr)) % (size)) == 0)
assert(IS_ALIGNED(heap_8, 8));
assert(IS_ALIGNED(heap_16, 16));
assert(IS_ALIGNED(heap_32, 32));
assert(IS_ALIGNED(heap_64, 64));
assert(IS_ALIGNED(heap_128, 128));
assert(IS_ALIGNED(heap_256, 256));
assert(IS_ALIGNED(heap_512, 512));
delete heap_8;
delete heap_16;
delete heap_32;
delete heap_64;
delete heap_128;
delete heap_256;
delete heap_512;
return 0;
}