You can allocate a std::vector which allocates aligned heap memory by defining your own allocator. You can allocate a c-style array on the stack using declspec align. But can you declare a tr1::array which guarantees that the element at index zero will be aligned?
Asked
Active
Viewed 1,114 times
4
-
How aligned do you need the memory to be? The implementation usually makes sure all objects are aligned. The exception is for "special" types like SSE vectors, which require 128-bit alignment. – jalf Aug 25 '10 at 11:42
-
Yes: new guarantees that the memory returned will be correctly aligned (as long as the requested memory is large enough to hold the object). So vector/Array and any dynamically allocated memory is guaranteed to be aligned for your object (as long as the size of the memory allocated is equal to or larger than your object). – Martin York Aug 25 '10 at 19:54
1 Answers
7
tr1::array
(and std::array
and boost::array
) are POD, so the memory occupied by the contents is coincident with the memory of the array
. So, allocate the array
however you need to, and construct it with placement new
.
typedef std::tr1::array< MyClass, ary_sz > AryT;
void *array_storage = aligned_allocation( sizeof( AryT ) );
AryT *ary = new( array_storage ) AryT( initial_value );

Potatoswatter
- 134,909
- 25
- 265
- 421