I'm porting a bit of an old code from C to C++. The old code uses object-like semantics, and at one point separates object destruction from freeing the now-unused memory, with stuff happening in between:
Object_Destructor(Object *me) { free(me->member1), free(me->member2) }
ObjectManager_FreeObject(ObjectManager *me, Object *obj) { free(obj) }
Is the above functionality possible in C++ using the standard destructor (~Object
) and a subsequent call to delete obj
? Or, as I fear, doing that would call the destructor twice?
In the particular case, the operator delete
of Object
is overridden as well. Is the definition I've read elsewhere ("when operator delete is used, and the object has a destructor, the destructor is always called) correct in the overridden operator case?
Best Solution
The
delete operator
is used to free memory, it doesn't change whether the destructor is called or not. First the destructor is called, and only after that is thedelete operator
used to deallocate the memory.In other words it's not possible to achieve the semantics you're aiming at with C++'s destructors and delete operators.
Sample:
Output: