Search code examples
c++comatlraii

Smart pointers release in FinalRelease explicitly


Some classes of project I'm working on look like this

class ATLCOMCLASS<CComObjectRootEx<ATLCOMCLASS> >
{
  ISomeInterfacePtr p;
  /*some stuff*/
  void FinalRelease()
  {
    p = NULL;
  }
}

ISomeInterfacePtr is defined by _COM_SMARTPTR_TYPEDEF. I don't understand why does it need to explicitly do p = NULL which means p->Release(), if this operation will be conducted in ATLCOMCLASS dtor automatically.

Could you exaplain me, please?


Solution

  • Technically, it doesn't have to do p = NULL at that point in the code, or explicitly at any point, because the destructor will release the smart pointer as you noted. However, explicitly releasing it gives you finer control over when it happens, which may be of use.

    Depending on the requirements of ISomeInterface, the program, and other factors, releasing p before this is destroyed might satisfy some program condition. In particular, if FinalRelease() is called by another method and not the dtor, then the cleanup is happening somewhere else and likely has a very different trigger. It could also be cleaned up and then some resources recreated in a sort of reset, or any number of other sequences.

    To figure out exactly why this is useful, assuming it's not a mistake, you'll need to work back up the possible program flow and see what's going on.