Assume we have a pointer to a com interface so my question is do we need to set the pointer to null after Release() call. Or else how COM handles it?
Func1()
{
.....
.....
pComInterface->Release();
pComInterface = NULL; //---> Does this required? If used, then what is the impact?
}
I assume pComInterface
is a raw pointer, declared as e.g.:
IFoo* pComInterface
No, you don't need to NULL it - it's just your local variable. A call of IUnknown::Release
is however mandatory since you notify the object that you release the pointer and the object can safely decrement its internal reference counter, if it has any.
If pComInterface
is a raw pointer to some COM interface, then from COM's point of view the important thing is to call Release()
to properly manage the object lifetime. (COM has no idea if you set the raw pointer to NULL
or not after a call to Release()
.)
However, from the point of view of good code quality, you should set the pointer to NULL
(or, better nullptr
in C++11) after calling Release()
, to be sure that you don't have a dangling reference to a previously released COM object, if you have some code following Release()
.
(It's a similar case to new
and delete
: you must call delete
after new
to properly release object's resources; you don't "need" to set the pointer to nullptr
after delete
, but it's a good coding practice to avoid dangling references to a deleted object.)
Moreover, even better is to use a smart pointer to manage the lifetime of COM object interfaces, like ATL::CComPtr
. In this way, proper calls to Release()
(and AddRef()
) are made automatically for you.
(Continuing the comparison with new
and delete
, it's the same suggestion as preferring smart pointers like shared_ptr
or unique_ptr
instead of raw owning pointers.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With