C++ memory alignment question

空扰寡人 提交于 2019-12-09 13:11:07

问题


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.


回答1:


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.




回答2:


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;
  };
};


来源:https://stackoverflow.com/questions/4445509/c-memory-alignment-question

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!