Again with placement new I've found an example on this forum like this:
char *buf = new char[sizeof(string)]; // pre-allocated buffer
string *p = new (buf) string("hi"); // placement new
string *q = new string("hi"); // ordinary heap allocation
But I think here
bufis a pointer to an allocated and Constructed dynamic array of default-init characters. So the characters in the array are default initialized and have an indeterminate values.I guess using the placement
newin the second line will constructs objects on the previously constructed array of objects.Why the user didn't call
operator newon the array allocation rather than usingnewexpression?:char *buf = static_cast<char*>(operator new[](sizeof(string)));After all I think if
buffis a pointer to a dynamic array of non-default-constructible objects then the code will fail to compile using the new expression rather than using the operator new function.Are my guesses correct?
Here is the link to the original answer: