Possible Duplicate:
Can placement new for arrays be used in a portable way?
I want to allocate array of object T and initialize object using object constructor. This is easy using c++ new :
T * pointerT = new T [arraySize];
It will call T constructor for all of the arraySize objects.
However, for some reason I have to use C memalign instead of new. In this case I end up to use following code
T * pointerT = (T*) memalign(64,arraySize * sizeof(T));
new (pointerT) T();
new (pointerT) T() calls T constructor only one time. However, I need to call T constructor for all objects not only the first one.
I do appreciate your help.
Do
new (pointerT) T()in a loop. Please keeppointerTinside an object whose destructor destroys the objects and callsfree(call it eg.aligned_vector), and in the constructor, do:This way, if a construction fails, you can bail out transactionally and not leak memory or resources.
For this purpose, the simplest in terms of reusability would be to implement your own alignment aware allocator and use
std::vector, which takes care of exception safety (and many other goodies) for you.Here is a sample allocator, C++11, with compile time alignment specification (please suggest enhancements and corrections):
Sample usage:
std::vector<T, aligned_allocator<T, 64>> v(42);constructs a vector with aligned storage and 64 elements.You can also do, in C++11
and you can now use
and enjoy an exception safe, move aware, iterators aware, range-based-for-loop aware, etc, vector with aligned storage.