5.3.4 [expr.new]
of the C++11 Feb draft gives the example:
new(2,f) T[5]
results in a call ofoperator new[](sizeof(T)*5+y,2,f)
.Here, x and y are non-negative unspecified values representing array allocation overhead; the result of the new-expression will be offset by this amount from the value returned by
operator new[]
. This overhead may be applied in all array new-expressions, including those referencing the library functionoperator new[](std::size_t, void*)
and other placement allocation functions. The amount of overhead may vary from one invocation of new to another. —end example ]
Now take the following example code:
void* buffer = malloc(sizeof(std::string) * 10);
std::string* p = ::new (buffer) std::string[10];
According to the above quote, the second line new (buffer) std::string[10]
will internally call operator new[](sizeof(std::string) * 10 + y, buffer)
(before constructing the individual std::string
objects). The problem is that if y > 0
, the pre-allocated buffer will be too small!
So how do I know how much memory to pre-allocate when using array placement-new?
void* buffer = malloc(sizeof(std::string) * 10 + how_much_additional_space);
std::string* p = ::new (buffer) std::string[10];
Or does the standard somewhere guarantee that y == 0
in this case? Again, the quote says:
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.
char*
. – Sugdennew
? I don't think it will influence performancee much because placement new is basically a no-op, and constructors for all objects in array have to be called separately anyway. – Ianthex
andy
additional space (had to find thex
value here, since it wasn't included)? If it is for when an exception occurs, then it should be stated in the standard. If it is compiler implementation specific, that makes it totally useless from a portability standpoint. – Peacockdelete[]
to know how many objects there are. – Sugdendelete[]
requires this, this should be defined in the standard somewhere as to what it contains, or at least that it should be either defined as a class/struct that has particular properties. – Peacockoperator new[]
andoperator delete[]
in whatever scope they are located in to deal with this extra overhead internally rather then having this overhead passed along with the minimal required space. I think that was the original intent, but if a constructor throws an exception, this can cause a problem if it's not known how many elements have been constructed. What's really missing from C++ is a way to define how to construct an array of elements. – Peacocknew[](std::size_t, void*)
Ugh, that's horrible (and I'm not sure I believe it - it's nonsensical). – Czarina