in this answer: https://stackoverflow.com/a/222578/4416169
with this code:
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
there is a comment that says:
keep in mind that the strings are destrcuted manually before deleting the buffer, thats what the comment below already assumes.
Strictly, it's undefined behaviour to call delete[] on the original char buffer. Using placement new has ended the lifetime of the original char objects by re-using their storage. If you now call delete[] buf the dynamic type of the object(s) pointed to no longer matches their static type so you have undefined behaviour. It is more consistent to use operator new/operator delete to allocate raw memory inteded for use by placement new.
Is this comment correct on what it claims? Should we instead create a buffer of void* pointers with operator new to create it and operator delete to delete it as in the following code?:
void *raw_memory = operator new(sizeof(int));
int *dynamicInt = new(raw_memory) int;
operator delete(raw_memory);
is this code^^ strictly equivalent to the following code?:
void *raw_memory = operator new[](sizeof(int));//notice the [] after new
int *dynamicInt = new(raw_memory) int;
operator delete[](raw_memory);//notice the [] after delete
or is it ok to simply use a char* buffer and do the usual array delete and new?