Matthieu N.
Matthieu N.

Reputation:

Allocation Target of std::aligned_storage (stack or heap?)

I've been trying to get my head around the TR1 addition known as aligned_storage. Whilst reading the following documents N2165, N3190 and N2140 I can't for the life of me see a statement where it clearly describes stack or heap nature of the memory being used.

I've had a look at the implementation provided by msvc2010, boost and gcc they all provide a stack based solution centered around the use of a union.

In short:

Note: In MSVC10, the following is the definition of the type of aligned_storage, in this case if the aligned_storage is an auto variable the data(_Val,_Pad) is created on the stack:

template<class _Ty, size_t _Len> 
union _Align_type
{   
   // union with size _Len bytes and alignment of _Ty
   _Ty _Val;
   char _Pad[_Len];
};

Note: This is NOT a trivial question. Please try and understand the question before posting an answer.

Upvotes: 4

Views: 2111

Answers (2)

Motti
Motti

Reputation: 114795

You typically don't need to align stuff on the heap since any allocation (new/malloc) returns memory at an address which is aligned to any type.

Upvotes: 0

James McNellis
James McNellis

Reputation: 355217

std::aligned_storage<Len, Align> just declares a member typedef (type).

The member typedef type shall be a POD type suitable for use as uninitialized storage for any object whose size is at most Len and whose alignment is a divisor of Align

(This is from the latest C++0x draft, N3225, 20.7.6.6 Table 53, but the language in the TR1 specification, N1836, is effectively the same except that in C++0x the Align template parameter has as its default argument the maximum alignment value.)

std::aligned_storage doesn't allocate any memory itself. You can create an object of type std::aligned_storage<Len, Align>::type and reinterpret that object as an object of any type that meets the requirements stated above.

Upvotes: 13

Related Questions