I am writing a memory-managing template class in which I want to create a C-style array of fixed size, to serve as a heap. I keep the objects stored in an array like this:
T v[SIZE];
As this only serves the role as a heap that can hold T objects, I don’t want the T default constructor to get automatically called for every object in the array.
I thought about the solution to define the heap like this:
char v[SIZE * sizeof(T)];
…but this will give me alignment problems.
Is there any better way to achieve this?
ADD: As I have special run time requirements, it is essential that this class doesn’t do any allocations on the global heap.
ADD 2: SIZE is a template argument and known at compile-time.
The standard containers use allocators to seperate allocation/deallocation from construction/destruction. The standard library supplies a single allocator which allocates on the heap.
This code declares an array big enough to hold
SIZEelements of typeTwith the correct allignment:The solution using
std::allocatorcan’t be used to declare an array on the stack, and as the standard containers require that custom allocators hold no state, a custom allocator can’t be portably used to allocate on the stack either.If your compiler doesn’t support
std::tr1::alignment_ofyou can useboost::alignment_ofinstead.