各位朋友们,
在使用类继承时,如果使用placement-new,则需要基类进行内存释放。否则,在一个已经被释放的对象上调用基类的析构函数。 我希望能够从派生类中执行内存释放操作。因此,我希望得到一些想法和建议!(注:我不使用placement-new也可以,但我想自定义内存管理而不是使用new/delete)。
以下是一个示例代码片段:
#include <cstdint>
#include <cstdio>
#include <new>
class CParent
{
public :
CParent() {
printf("CParent()\n");
}
virtual ~CParent() {
printf("~CParent()\n");
}
};
class CAllocator
{
private :
void Free(uint8_t *buffer) {
printf("CAllocator::Free(%p)\n", buffer);
delete [] buffer;
}
class CChild : public CParent
{
public :
CChild(CAllocator &allocator, uint8_t *buffer)
: mAllocator(allocator), mBuffer(buffer)
{
printf("CChild()\n");
}
~CChild() {
printf("~CChild()\n");
mAllocator.Free(mBuffer);
}
private :
CAllocator &mAllocator;
uint8_t *mBuffer;
};
public :
CParent *Alloc() {
uint8_t *buffer = new uint8_t[sizeof(CChild)];
printf("CAllocator::Alloc() = %p\n", buffer);
return new (buffer) CChild(*this, buffer);
}
};
int main()
{
CAllocator allocator;
CParent *object = allocator.Alloc();
// NB: Can't do `delete object` here because of placement-new
object->~CParent();
return 0;
}
这将产生以下输出:
CAllocator::Alloc() = 0x2001010
CParent()
CChild()
~CChild()
CAllocator::Free(0x2001010)
~CParent()
所以,
~CParent()
在内存被释放后被调用...感谢您的帮助!
mAllocator.Free(mBuffer);
。你不是在构造函数中分配了那块内存吗?那么对于释放操作,你应该在析构函数调用完成后再进行。 - Praetorian