How placement new can be done on stack

162 Views Asked by At

Consider the following codes:

char mem[sizeof(char)];
void* p = mem;
f = new(p) char;

Since the memory for variable mem should be on stack So, why doesn't this piece of memory get collected automatically in the end.

1

There are 1 best solutions below

1
On

The memory IS collected automatically.

But the destructor won't be called automatically. When you use placement new, you should pair that with a manual destructor call. For char this doesn't really matter of course, since the destructor is trivial.