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?
Using the
new
expression does two things, it calls the functionoperator new
which allocates memory, and then it uses placement new, to create the object in that memory. Thedelete
expression calls the object's destructor, and then callsoperator delete
. Yeah, the names are confusing.Since in your case, you used placement new manually, you also need to call the destructor manually. Since you allocated the memory manually, you need to release it manually.
However, placement new is designed to work with internal buffers as well (and other scenarios), where the buffers were not allocated with
operator new
, which is why you shouldn't calloperator delete
on them.The purpose of the
buffer_struct
class is to create and destroy the storage in whatever way, whilemain
takes care of the construction/destruction ofMyClass
, note how the two are (almost*) completely separate from each other.*we have to be sure the storage has to be big enough