I have a C++ object that's being created in a plugin in a memory buffer provided by the host application with the placement new operator in a manner similar to the following code:
MyClass* createObject(void* inNewBlock)
{
MyClass* elementAddr = static_cast<MyClass*>(inNewBlock);
new (elementAddr) MyClass(); // Placement new into pre-allocated memory
}
I know that I can't delete an object created this way, but I wondered if there is a way to null out the memory and reallocate the object at a later point if I need to like so:
void removeObject(MyClass* object)
memset(object, NULL, sizeof(MyClass));
}
void restoreObject(MyClass* object)
{
new (object) MyClass(); // Placement new into pre-allocated memory
}
The code above doesn't work. I've tried it, and the host application hangs or crashes when I call restoreObject()
. I was hoping someone could explain to me why this doesn't work and what an alternative might be.