I don’t want constructor called. I am using placement new.
I just want to allocate a block of T.
My standard approach is:
T* data = malloc(sizeof(T) * num);
however, I don’t know if (data+i) is T-aligned. Furthermore, I don’t know if this is the right “C++” way.
How should I allocate a block of T without calling its constructor?
Firstly, you are not allocating a "block of
T*". You are allocating a "block ofT".Secondly, if your
Thas non-trivial constructor, then until elements are constructed, your block is not really a "block of T", but rather a block of raw memory. There’s no point in involvingThere at all (except for calculating size). Avoid *pointer is more appropriate with raw memory.To allocate the memory you can use whatever you prefer
or
or
or
Later, when you actually construct the elements (using placement new, as you said), you’ll finally get a meaningful pointer of type
T *, but as long as the memory is raw, usingT *makes little sense (although it is not an error).Unless your
Thas some exotic alignment requirements, the memory returned by the above allocation functions will be properly aligned.You might actually want to take a look at the memory utilities provided by C++ standard library:
std::allocator<>withallocateandconstructmethods, and algorithms asuninitialized_filletc. instead or trying to reinvent the wheel.