0

Can someone explain clearly what is the difference between .Release() and ->Release() on a CComPtr ?

To be precise how the memory management happens in either case?

M.M
  • 138,810
  • 21
  • 208
  • 365
Brahmaprasad R
  • 131
  • 2
  • 9
  • @tartanllama Too bad the most up-voted answer in the duplicate leads with such an imprecise statement. – juanchopanza Aug 11 '15 at 09:19
  • 1
    I don't think this is an appropriate duplicate, in this case they are both overloaded operators – M.M Aug 11 '15 at 09:20
  • Wow, most of those answers completely ignore operator overloading. – juanchopanza Aug 11 '15 at 09:24
  • Simply step in with debugger into `CComPtr::Release` and you will immediately see a few lines of code that stand between further call to `IUnknown::Release` on the managed pointer. – Roman R. Aug 11 '15 at 09:29
  • ->Release() is almost certainly a bug, .Release() is something you should not do since the point of using CComPtr is to let it take care of it automatically. Favor the `delete` operator instead, it is unambiguous. – Hans Passant Aug 11 '15 at 10:01

1 Answers1

5

The operator-> function of CComPtr yields a raw interface pointer to the object being managed. (but see below)

So, calling ->Release() will release the object (i.e. decrement its internal reference count).

The .Release() function will call ->Release(), and make the smart pointer stop managing the raw interface pointer.

The latter is usually what you want to do. If you call ->Release() then smart pointer doesn't know this , and when the smart pointer's destructor runs, it will call ->Release() again which is bad (double release).

According to this page, recent versions of ATL actually have operator-> return a proxy class which hides AddRef and Release, so you should get a compilation error if you try ->Release(), instead of getting a double delete.

M.M
  • 138,810
  • 21
  • 208
  • 365