我一直在阅读,当您使用placement new时,您必须手动调用析构函数。
考虑以下代码:
// 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();
据我所知,操作员delete
通常会调用析构函数,然后释放内存,对吗?那么我们为什么不使用delete
呢?
delete pMyClass; //what's wrong with that?
nullptr
在第一种情况下,我们在调用析构函数后被迫将 pMyClass 设置为:
pMyClass->~MyClass();
pMyClass = nullptr; // is that correct?
但是析构函数没有释放内存,对吧? 那么这会是内存泄漏吗?
我很困惑,你能解释一下吗?