开发者

C++ memory alignment question

A line of code is worth a thousand words :) Here is my problem:

/* 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);

Can I expect that all assertions pass on platforms with SSE support? Thank you.

EDIT. Partial answer. I did some test with VS2008, GCC and ICC. MS compiler did align both ptr and ptr2, but GCC and ICC failed to align ptr2.


Is there any guarantee of alignment of address return by C++'s new operation?

In other words, you can use the standard to justify your assumption that it should work, but in practice, it may blow up in your face.

Visual C++ 6 did not align doubles allocated via new properly, so there you go.


C++0x provides a new construct (in [meta.type.synop] 20.7.6.6 other transformations):

std::aligned_storage<Length, Alignment>

which is guaranteed to be always correctly aligned as far as I recall.

The second parameter is optional, and defaults to the most stringent requirement possible (so that it's always safe not to precise it, but that you may pack your types more compactly if you are willing to try).

Apart from bugs, the compiler is bound to honor the requirement. If you do not have C++0x, this may be found in the tr1 namespace or on Boost.

You're the only one who can test that your particular compiler does honor this request :)

Note: on gcc-4.3.2, it is implemented as:

template<std::size_t _Len, std::size_t _Align = /**/>
struct aligned_storage
{
  union type
  {
    unsigned char __data[_Len];
    struct __attribute__((__aligned__((_Align)))) { } __align;
  };
};
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜