That's a good approach, but sometimes you can't do it in C++. (At least with C++03.) Consider:
template <class T>
T* new_align_1d(size_t d1, unsigned int align)
{
void* ptr = _malloc_align(d1 * sizeof(T), align);
return new (ptr) T[d1];
}
So, I'm defining a function
new_align that takes a size and an alignment. I allocate enough space for a 1-dimensional array of the given size on that alignment, then use the placement operator to construct the actual objects in that place. Then return the pointer. Pretty straightforward. So let's generalize one dimension up:
template <class T, size_t d2>
? new_align_2d(size_t d1, unsigned int align)
{
void* ptr = _malloc_align(d1 * d2 * sizeof(T), align);
return new (ptr) T[d1][d2];
}
You can probably see what I'm doing here. So what's the return type? And what's the syntax for specifying it? Since it's a template, we can't define a typedef to help us. (C++0x should allow that with parameterized typedefs.) The answer surprised me - I really had to look at the grammar and mechanically figure out what it was going to be.
(Yes, I have to pass d2 as a template parameter - it's part of the type of the array and must be known at compile time.)