C++ C++;内存对齐问题

C++ C++;内存对齐问题,c++,gcc,alignment,icc,visual-studio,C++,Gcc,Alignment,Icc,Visual Studio,一行代码胜过千言万语:)这是我的问题: /* Platform specific 16-byte alignment macro switch. On Visual C++ it would substitute __declspec(align(16)). On GCC it substitutes __attribute__((aligned (16))). */ #define ALIGN_16 ... struct ALIGN_16 A {...}; A* ptr = n

一行代码胜过千言万语:)这是我的问题:

/* Platform specific 16-byte alignment macro switch.
   On Visual C++ it would substitute __declspec(align(16)).
   On GCC it substitutes __attribute__((aligned (16))).
*/
#define ALIGN_16 ...

struct ALIGN_16 A {...};

A* ptr = new A;
A* ptr2 = new A[20];

assert(size_t(ptr) % 16 == 0);

for (int i=0; i<20; ++i)
    assert(size_t(ptr2+i) % 16 == 0);

assert(sizeof(A) % 16 == 0);
/*特定于平台的16字节对齐宏开关。
在Visual C++中,它将替代AyO-DESPECEC(AlGIN(16))。
在GCC上,它替换了uuu属性uuuu((对齐(16)))。
*/
#定义对齐_16。。。
结构对齐_16 A{…};
A*ptr=新的A;
A*ptr2=新的A[20];
断言(大小(ptr)%16==0);
对于(int i=0;i

换句话说,你可以用这个标准来证明你的假设是正确的,但实际上,它可能会在你面前爆炸


Visual C++ 6没有正确地通过<代码>双份<代码> >分配< <代码> > <代码>,所以你可以去了。

< P> C++ +0x提供了一个新的构造(在<强> [元类型.Syop] 20.7.6其他转换中):


我脑子里想不出来。我在想,数组的每个元素是否都对齐。标准保证正确分配的数组的元素对于所讨论的类型正确对齐。但是,对齐是一个实现细节,理论上可能是一个字节(即压缩对齐)更新的编译器呢?GCC 4.xx和VS 2008?我不知道有哪种编译器提供了与
new
malloc
的16字节对齐,这意味着在实践中,断言将失败。@jalf,是的,这就是我所想的。我认为C++0x“支持”它,但考虑到HeapAlloc间接保证8字节(由于默认的打包选项是windows数据结构的8字节对齐方式),我怀疑这种情况会很快发生。不过,对象分配了
new
,这(通常)不符合特定的对齐要求。(它通常只提供8字节对齐的内存,对于大多数用途来说已经足够了)@jalf:但是标准要求
new
返回一个适当对齐的内存块(从3.7.4.1[basic.std.dynamic.allocation]$2),除非我不理解,以便可以将其转换为具有基本对齐要求(3.11)和3.11[basic.align]的任何完整对象类型的指针$2基本对齐由小于或等于所有上下文中实现支持的最大对齐表示,该对齐等于alignof(std::max_align_t)(18.2)…因此,我想说,如果
new
只返回8字节对齐的值,并且
std::max_align\u t
优于8,那么实现是不一致的。
std::aligned_storage<Length, Alignment>
template<std::size_t _Len, std::size_t _Align = /**/>
struct aligned_storage
{
  union type
  {
    unsigned char __data[_Len];
    struct __attribute__((__aligned__((_Align)))) { } __align;
  };
};