Circular reference with shared_ptr [duplicate]

  c++, c++14, shared-ptr

I’m trying to understand cyclic reference with shared_ptrs
In first case I want to understand what really happens. When x goes out of scope does it firstly try to delete its attribute x_ which hold reference to X so it cannot be deallocated since x also has reference to the resource ?
In second case why there’s no Circular reference as Com holds a Sup and from Sup is created a Com with Sup ?
I would like to know from both cases what exactly happends to understand it better.
Thanks you.

// 1 Circular reference

struct X 
{
  X()
  {
      std::cout<<"CXn";
  }
  ~X()
  {
      std::cout<<"DXn";
  }
  std::shared_ptr<X> x_;
};
using Xptr = std::shared_ptr<X>;
int main()
{
    Xptr x = std::make_shared<X>();
    x->x_ = x;
    std::cout<< " --x.use_count()--" << x.use_count() << std::endl; // use_count 2.
    return 0;
}

// 2 No Circular reference

  struct Com;
    struct Sup: public std::enable_shared_from_this<Sup>
    {
        Sup(int id):id_(id)
        {
            std::cout<<"***CS: " << id_ << std::endl;
        }
        ~Sup()
        {
            std::cout<<"###DestrSup " << id_ << std::endl;
        }
        void d()
        {
            auto com = std::make_shared<Com>(7, shared_from_this());
        }
        int id_;
    };
    using SupPtr = std::shared_ptr<Sup>;
    
    struct Com
    {
      Com(int id, SupPtr supPtr):id_(id), supPtr_(supPtr)
      {
        std::cout<<"***ConstrCom: " << id_ << std::endl;
      }
      ~Com()
      {
         std::cout<<"###DestrCom: " << id_ << std::endl;
      }
      int id_;
      SupPtr supPtr_; 
    };
    
    int main()
    {   
        auto sup = std::make_shared<Sup>(1);
        auto com = std::make_shared<Com>(1, sup);
        auto com2 = std::make_shared<Com>(2, sup);
        auto com3 = std::make_shared<Com>(3, sup);
        sup->d();
        return 0;
    }

Source: Windows Questions C++

LEAVE A COMMENT