问题
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?
回答1:
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 );
来源:https://stackoverflow.com/questions/3564842/how-to-make-tr1array-allocate-aligned-memory