I have a basic interface (using Microsofts C++ syntax for interfaces in Visual Studio 2013) which exposes simple functions like this:
__interface IDisposable {
void Dispose();
};
__interface IBase : public IDisposable {
void Foo();
void Bar();
};
There is a specific type of classes which has to inherit those methods thus these classes have this structure:
class Derived : public IBase {
public:
Derived();
~Derived();
void Dispose();
void Foo();
void Bar();
}
These classes do have some variables as well and I wanted to use smart pointers but those pointers did produce leaks because the destructor ~Derived()
isn't called in the following scenario:
- I am having a
Stack<IBase*>
which handles a bunch of those objects (e.g.Derived
,Derived2
, etc.). - Once the top-most element (
pCurrent
) should be removed from the stack with the corresponding data (m_Data
) I am calling the method to dispose resources:((IDisposable*)pCurrent->m_Data)->Dispose();
- This call is followed by a
delete pCurrent->m_Data
which apparently tries to invoke~IBase()
which doesn't exist obviously as it is an interface. Therefore the mentioned~Derived()
won't be called as well and any smart pointers inDerived
would not be deleted as well and this causes serious memory leaks.
Surprisingly a manual deletion works:
auto p = new Derived();
delete p; // ~Derived() is properly called as we are not handling a IBase* object
I was thinking about using a virtual destructor, but there is no way to define destructors in those interfaces to make ~Derived()
virtual as well.
Is there a better approch to be able to call the right destructors?