0

I'm trying to understand cyclic reference with shared_ptrs In this 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 what exactly happens to understand it better. Thanks you.

 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;
    }
  • There's no circular reference in this code. – Eljay Oct 24 '21 at 13:34
  • @Eljay, I want explanation for why thre's no circular reference, thanks – Dean Marek Oct 24 '21 at 13:36
  • To have a circular reference you need to have object one holding a shared_ptr to object two in a member variable, while object two also holds a shared_ptr to object one in a member variable. This code does not have that kind of relationship. – Eljay Oct 24 '21 at 13:39

0 Answers0