Главная страница | назад





Article #18716: Calling Release on returned interface pointers

 Question and Answer Database
FAQ3716C.txt Calling Release on returned interface pointers
Category :ActiveX/OLE/COM/ActiveForm
Platform :All
Product : All32Bit
Question:
I am a little hazy on whether the Release() function ever has to be
called for the various types of interface classes generated in a
xxx_TLB.h file. I know that for smart interfaces, the interface is
automatically released when the smart interface goes out of scope. I
expect that for just plain interfaces, which are directly derived from
IDispatch, and handed back to me, I do have to call its Release()
function when I am finished using it. What about dispinterfaces ? Is the
interface which it binds to released when the dispinterface goes out of
scope ? Some elucidation of this matter would be welcome from anyone who
knows about it.
I am particularly interested because various interface functions return,
or specifies a parameter that returns, another interface. The easiest
way to deal with this second interface is to stuff it in its equivalent
dispinterface but I am not sure whether or not I must call Release() on
this dispinterface when I am through using it.
Answer:
Yes, you're expected to call Release on interfaces returned as a parameter.
Typically the sender will do an AddRef() before sending it over. One
approach is to put the interface returned in a smart wrapper. I purposely
made the wrappers refrain from invoking 'AddRef' when assigned an interface
pointer for this particular case.
(NOTE: There are two trends with smart wrappers receiving raw interfaces
pointers: ATL's CComPtr, for example, does an AddRef in the constructor that
takes a raw interface pointer as well as the assignment operator that takes
a raw interface. Consequently, there's a lot of ATL code that calls
Wrapper->Release() after the interface has been assigned to the smart
object; The other trend is the one used by the wrappers in UTILCLS.H. The
wrappers from the OCF framework [which I worked on eons ago] also followed
the latter trend).
This rule applies to DispInterfaces too. If a property returns an
LPDISPATCH, you'll be expected to call Release() on it when you're done.
Again, you can put the interface in a smart wrapper and let the destructor
of the smart wrapper handle the cleanup.
8/26/98 2:26:01 PM

Last Modified: 01-SEP-99