【发布时间】:2011-09-05 21:49:33
【问题描述】:
我有一个 C++ 对象,该对象是在主机应用程序提供的内存缓冲区中的插件中创建的,使用placement new 运算符,其方式类似于以下代码:
MyClass* createObject(void* inNewBlock)
{
MyClass* elementAddr = static_cast<MyClass*>(inNewBlock);
new (elementAddr) MyClass(); // Placement new into pre-allocated memory
}
我知道我不能删除以这种方式创建的对象,但我想知道是否有办法清空内存并在以后需要时重新分配对象:
void removeObject(MyClass* object)
memset(object, NULL, sizeof(MyClass));
}
void restoreObject(MyClass* object)
{
new (object) MyClass(); // Placement new into pre-allocated memory
}
上面的代码不起作用。我试过了,当我调用restoreObject() 时,主机应用程序挂起或崩溃。我希望有人可以向我解释为什么这不起作用以及可能的替代方法。
【问题讨论】:
-
你能得到堆栈跟踪吗?可能对象指向的内存不够大。
-
您能解释一下“稍后重新分配 对象”是什么意思吗?
标签: c++ memory-management