Should the pointer be set to zero after calling the COM Release () function?

Suppose we have a pointer to a com interface, so my question is whether to set the pointer to zero after calling Release (). Or how does COM handle it?

Func1() { ..... ..... pComInterface->Release(); pComInterface = NULL; //---> Does this required? If used, then what is the impact? } 
+4
source share
2 answers

If pComInterface is a raw pointer to some COM interface, then from the COM point of view it is important to call Release() to properly control the lifetime of the object. (COM has no idea if you set the raw pointer to NULL or not after calling Release() .)

However, in terms of good code quality, you should set the pointer to NULL (or, better, nullptr in C ++ 11) after calling Release() to be sure t has a dangling link to a previously released COM object, if you have there is code following Release() .

(This is similar to new and delete : you must call delete after new in order to properly release the resources of the object, you do not need to "set the pointer to nullptr after delete , but it is good coding practice to avoid dangling references to the remote object.)

Moreover, it is even better to use a smart pointer to control the lifetime of COM object interfaces, such as ATL::CComPtr . This way, the correct calls to Release() (and AddRef() ) are created automatically for you. (Continuing the comparison with new and delete , this is the same assumption as preferred smart pointers such as shared_ptr or unique_ptr instead of raw ownership pointers.)

+3
source

I assume pComInterface is a raw pointer declared, for example:

IFoo* pComInterface

No, you do not need to specify NULL - this is just your local variable. However, calling IUnknown::Release is mandatory, since you are notifying the object that you are freeing the pointer, and the object can safely decrease its internal reference count, if any.

+6
source

All Articles