[C++] is a char array aligned for any type

Started by
3 comments, last by NightCreature83 12 years, 5 months ago
Just wondering if a char x[100]; would be aligned for any type.
What I'm trying to do is to create a small_array< some_type, some_unsigned > which currently has an array 'some_type array[some_unsigned]'. If some_unsigned elements are used, it will dynamically allocate memory for the extended size, otherwise no memory allocation is done.
The problem is that array will call all constructors even if 0 elements are in use. So what I'm hoping to do is to create a char array[some_arbritary_size] and when an element is added, simply placement new the new element at its location in the char array.
Basically my question is, does the c++ standard say a char array is aligned for any type?
Advertisement
No, not if allocated on the stack or as a member variable. I'd have to double check the exact wording, but IIRC, a char array obtained through new [] should be able to be used for storage for any type. (Edit: yeah 5.3.4 paragraph 10 of ISO/IEC 14882:1998 supports it.)
Ok, thanks.
You can of course use compiler specific extensions to make it aligned. For gcc "char x[100] __attribute__((aligned(16)));" will give you 16 byte alignment. For MSVC it's: "char x[100] __declspec(align(16));"

Also note that the standard says that unions are aligned for the member with the biggest alignment requirement, which you can use to get things aligned. For example "union {int align; char x[100];};" would give the char array the same alignment as an int.

You can of course use compiler specific extensions to make it aligned. For gcc "char x[100] __attribute__((aligned(16)));" will give you 16 byte alignment. For MSVC it's: "char x[100] __declspec(align(16));"

Also note that the standard says that unions are aligned for the member with the biggest alignment requirement, which you can use to get things aligned. For example "union {int align; char x[100];};" would give the char array the same alignment as an int.

If you have to target multiple platforms you are best of creating a define for your allignments and use that instead of the naked calls. Then you can compile with it on or off as well depending on your configuration flags.

Worked on titles: CMR:DiRT2, DiRT 3, DiRT: Showdown, GRID 2, theHunter, theHunter: Primal, Mad Max, Watch Dogs: Legion

This topic is closed to new replies.

Advertisement