Current draft standard explicitly states that placement new[]
can have a space overhead:
This overhead may be applied in all array new-expressions, including those referencing the library function operator new[](std::size_t, void*) and other placement allocation functions. The amount of overhead may vary from one invocation of new to another.
So presumably they have something in mind, why a compiler need this overhead. What is it? Can a compiler use this overhead for anything useful?
In my understanding, to destruct this array, the only solution is to call destructors in a loop (am I right on this?), as there is no placement delete[]
(btw, shouldn't we have placement delete[]
to properly destruct the array, not just its elements?). So the compiler doesn't have to know the array length.
I thought as this overhead cannot be used for anything useful, compilers don't use it (so this is not an issue in practice). I've checked compilers with this simple code:
#include <stdio.h>
#include <new>
struct Foo {
~Foo() { }
};
int main() {
char buffer1[1024];
char buffer2[1024];
float *fl = new(buffer1) float[3];
Foo *foo = new(buffer2) Foo[3];
printf("overhead for float[]: %d\n", (int)(reinterpret_cast<char*>(fl) - buffer1));
printf("overhead for Foo[] : %d\n", (int)(reinterpret_cast<char*>(foo) - buffer2));
}
GCC and clang doesn't use any overhead at all. But, MSVC uses 8 bytes for the Foo
case. For what purpose could MSVC use this overhead?
Here's some background, why I put this question.
There were previous questions about this subject:
- Array placement-new requires unspecified overhead in the buffer?
- Can placement new for arrays be used in a portable way?
As far as I see, the moral of these questions is to avoid using placement new[]
, and use placement new
in a loop. But this solution doesn't create an array, but elements which are sitting next to each other, which is not an array, using operator[]
is undefined behavior for them. These questions are more about how to avoid placement new[]
, but this question is more about the "why?".