I'm learning how to use placement new in C++ and I find an example as below:
int main()
{
// buffer on stack
unsigned char buf[100];
// using placement new
Complex *pe = new (buf) Complex(2.6, 3.9);
pe->print();
// No delete : Explicit call to Destructor.
pe->~Complex();
return 0;
}
I can understand what the piece of code is doing but I have a question:
Is it possible to remove pe->~Complex()
?
As my understanding, the object pe
is located on the buf
, so it is the buf
who is charge of managing the memory. I mean that calling the destructor of pe
is not necessary. Am I right?
If there is a new object
in the class Complex
, obviously we have to delete
it in the destructor. Here my question is: must the new object
in Complex
be located on the buf
? Or it may be located on any memory of the stack (just like the normal new
)?