【发布时间】:2015-05-20 15:47:32
【问题描述】:
同学们,
在类层次结构上使用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);。您不是从构造函数中分配内存,是吗?然后你应该对释放做同样的事情,在析构函数调用完成后调用它。
标签: c++ placement-new