I need to construct an array of objects from a previously allocated block of memory. However, I cannot understand in what way ::operator new[]()
is different from <
They're both allocation functions and thus they're both mandated to return suitable storage for the requested size (here that's sizeof(J) * size
). That's why they make no difference in your code.
Where they differ is that operator new
is the allocation function that is looked up in a non-array new expression (e.g. new J
), whereas operator new[]
is the allocation function that is looked up in an array new expression (e.g. new J[1]
). This allows customization if a program has a particular strategy to allocate memory for arrays that differ from the strategy for allocating memory for single objects. If no such customization is needed then operator new[]
can just delegate to operator new
(and this is in fact what is mandated for the allocation functions provided by the implementations, i.e. ::operator new
and ::operator new[]
). So that difference isn't relevant for your code.
You're misusing the new
.
The point of using new []
is that it calls the constructor for each and every element of the array being allocated. delete[]
does the same for the destructors.
You're using placement new
and manually calling the constructors and destructors, missing the whole point.