C++ placement new
why is it using a char array to provide memory space for the placement new?
Why not? char
is the smallest type that C++ defines, and on virtually every implementation, it is one byte in size. Therefore, it makes a good type to use when you need to allocate a block of memory of a certain size.
C++ also has very specific mechanics about how arrays of char
(and only char
are allocated. A new char[*]
, for example, will not be aligned to the alignment of char
. It will be aligned to the maximum normal alignment for any type. Thus, you could use it to allocate memory and then construct any type into that memory.
Also the last line in the code above is allocating memory for an array of double, how is that possible when the original memory space contains a char array?
It is not allocating anything. It is constructing an array, using the memory you have given it. That's what placement new does, it constructs an object in the memory provided.
If the placement new is using the memory space of the char array, does this mean when we allocate the double array it overwrites the char array in that memory?
Yes.
Yes, the char array and the double array would overlap, more specifically they would start at the same address in memory, i.e. (long)buffer
and (long)pd1
would be the same. We can emphasize the overlap even more by making the byte sizes match (assuming sizeof(char) == 1
):
const int N = 5;
char buffer[N * sizeof(double)];
double *pd1 = new (buffer) double[N];
Yes, if you modify the data pd1
points to, then the data buffer
points to would also be modified. And the other way round as well. (See also the GCC flag -fstrict-aliasing
to learn about how compiler optimizations work with such an overlap.)