Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c++

interface

com

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?
}
like image 717
Rahul Sundar Avatar asked Dec 27 '22 07:12

Rahul Sundar


2 Answers

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.

like image 100
Roman R. Avatar answered Dec 28 '22 21:12

Roman R.


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.)

like image 24
Mr.C64 Avatar answered Dec 28 '22 20:12

Mr.C64