Question

I've been reading somewere that when you use placement new then you have to call the destructor manually.

Consider the folowing code:

   // Allocate memory ourself
char* pMemory = new char[ sizeof(MyClass)];

// Construct the object ourself
MyClass* pMyClass = new( pMemory ) MyClass();

// The destruction of object is our duty.
pMyClass->~MyClass();

As far as I know operator delete normally calls the destructor and then deallocates the memory, right? So why don't we use delete instead?

delete pMyClass;  //what's wrong with that?

in the first case we are forced to set pMyClass to nullptr after we call destructor like this:

pMyClass->~MyClass();
pMyClass = nullptr;  // is that correct?

BUT the destructor did NOT deallocate memory, right? So would that be a memory leak?

I'm confused, can you explain that?

No correct solution

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top