【问题标题】:boost::shared_ptr use_countboost::shared_ptr use_count
【发布时间】:2009-05-21 00:41:18
【问题描述】:

我试图了解以下代码中发生了什么。当object-a被删除时,它的shared_ptr成员变量object-b是否因为object-c持有object-b的shared_ptr而留在内存中?

    class B
    {
    public:
       B(int val)
       {
          _val = val;
       }
       int _val;
    };

    class A
    {
    public:
       A()
       {
          _b = new B(121);
       }
       boost::shared_ptr<B> _b;
    };

    class C
    {
    public:
       C()
       {
       }

       void setRef( boost::shared_ptr<B> b)
       {
          _b = b;
       }
       boost::shared_ptr<B> _b;
    };

    int main()
    {
       C c;
       {
          A *a = new A();       
          cout << "a._b.use_count: " << a->_b.use_count() << endl;
          c.setRef(a->_b);
          cout << "a._b.use_count: " << a->_b.use_count() << endl;
                  delete a;
       }
       cout << c._b->_val << endl;
    }

【问题讨论】:

    标签: c++ pointers shared-ptr


    【解决方案1】:

    不,当a被删除时,a->_b(指针本身)将不复存在。

    a->_b 指向的对象会继续存在,因为 c._b 仍然指向它。

    【讨论】:

      【解决方案2】:

      A 对象将在其块末尾删除a 后立即被清理。但它包含的 shared_ptr 随后被复制,增加了它的引用计数。

      因此,B 对象在c.setRef 之后的引用计数为 2(由A 对象和C 对象的shared_ptr 引用)。当a 在其块的末尾被删除时,B 对象的引用计数再次下降到1,因为现在只有c 的 shared_ptr 正在引用它。

      c 在 main 结束时被销毁后,它的 shared_ptr 也将作为 c 销毁的一部分被销毁,现在随着引用计数降至零,指向的 B对象将被shared_ptr删除。

      所以,B-object 的引用计数:

      0: before existence of a.
      1: from start of lifetime of a until c.setRef
      2: from c.setRef until copy of its parameter
      3: from copy of c.setRef''s parameter until return of it
      2: from return of c.setRef until end of a''s block
      1: from end of a''s block until end of main
      0: after main returned (object doesn''t exist anymore now)
      

      【讨论】:

        【解决方案3】:

        shared_ptr 的目标将保持活动状态,直到对它的最终引用被删除。在这种情况下,这将是 C 实例超出范围的时候。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2018-07-30
          • 1970-01-01
          • 1970-01-01
          • 2022-01-03
          • 1970-01-01
          • 1970-01-01
          • 2022-12-12
          • 1970-01-01
          相关资源
          最近更新 更多