I think you dont understand the COM concept.
A simple implementation of a COM object:
class iUnknownImpl : public IUnknown
{
public:
virtual HRESULT __stdcall QueryInterface(REFIID riid,void** ppv)
{ return IID_IUnknown==riid?(*(IUnknown**)ppv=this,AddRef(),S_OK):E_NOINTERFACE; }
virtual unsigned long __stdcall AddRef()
{ return InterlockedIncrement(&_ref); }
virtual unsigned long __stdcall Release()
{ if(InterlockedDecrement(&_ref)) return _ref; delete this; return 0; }
iUnknownImpl(){ _ref=1; }
protected:
virtual ~iUnknownImpl(){ ASSERT(0==_ref); }
private:
long _ref;
};
You see if you want to hold an interface pointer - you have to call
AddRef()
. Other threads can meanwhile release the interface. If you dont need the interface anymore you must call
Release()
(once). If you want to cast an interface to another you have to call
QueryInterface()
. Remember: every call of
AddRef()
and
QueryInterface()
needs one
Release
.
After Release your pointer is invalid the object can be destroyed.
More AddRef's than Release's generate memory leaks. More Release's than AddRef's makes your app crash.
Regards.