smart pointer release

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • George2
    New Member
    • Dec 2007
    • 200

    smart pointer release

    Hello everyone,


    About the release method implementation of smart pointer of COM, there are two approaches below, and approach 1 is preferred is recommended by Inside COM -- should be better.

    Anyone know why approach 1 is better than approach 2?

    (m_pI is interface pointer to a COM interface of type T, and it is a member variable of the COM smart pointer class)

    Approach 1:

    Code:
    void Release()
    {
        if (m_pI != NULL)
        {
            T* pOld = m_pI;
            m_pI = NULL;
            pOld->Release();
        }
    }
    Approach 2:

    Code:
    void Release()
    {
        if (m_pI != NULL)
        {
            m_pI -> Release();
            m_pI = NULL;
        }
    }

    thanks in advance,
    George
  • weaknessforcats
    Recognized Expert Expert
    • Mar 2007
    • 9214

    #2
    I have no idea since the destructor of CComPtr uses Approach 2.

    Comment

    • George2
      New Member
      • Dec 2007
      • 200

      #3
      Hi weaknessforcats ,


      Any comments?

      --------------------
      Imagine this situation: object A holds a smart pointer to object B,
      which in turn holds a smart pointer to object A. For whatever reason, A
      decides to release its reference on B, by calling Release() on the smart
      pointer. This happens to be the last reference, so B destroys itself. In
      its destructor, it releases its reference on A - again by calling
      Release(). This, too, happens to be the last reference on A (the two
      objects kept each other alive with a circular reference), so in its
      destructor A calls Release() on its smart pointer to B.

      The bottom line of this scenario is that smart pointer's Release() ends
      up being called from itself, recursively. Approach 1 handles this
      gracefully, but Approach 2 will enter an infinite recursion.
      --------------------

      Originally posted by weaknessforcats
      I have no idea since the destructor of CComPtr uses Approach 2.

      regards,
      George

      Comment

      Working...