c++ - why memory leak when use circular reference in boost::shared_ptr -


in follow code memory leak happened, have doubt that. in test() fun:

#include <string> #include <iostream> #include <boost/shared_ptr.hpp> #include <boost/weak_ptr.hpp>  class parent; class children;  typedef boost::shared_ptr<parent> parent_ptr; typedef boost::shared_ptr<children> children_ptr;  class parent { public:     ~parent() { std::cout <<"destroying parent\n"; }  public:     children_ptr children; };  class children { public:     ~children() { std::cout <<"destroying children\n"; }  public:     parent_ptr parent; };  void test() {     parent_ptr father(new parent());     children_ptr son(new children);      father->children = son;// parent_ptr_count=1, children_ptr_count=2     son->parent = father;// parent_ptr_count=2, children_ptr_count=2    //1,2,3 see note below }  void main() {     std::cout<<"begin test...\n";     test();     std::cout<<"end test.\n"; } 
  1. // childern_ptr pop stack, think childern_ptr_count-- , parent_ptr_count--

  2. // parent_ptr pop stack, think childern_ptr_count-- , parent_ptr_count--

  3. // in fact, didn't that, why?

i hope can me, thank much.

i believe scenario in example: https://visualstudiomagazine.com/articles/2012/10/19/circular-references.aspx

this cyclic reference, , solution have 1 of pointers weak pointer. although article c++11's implementation of shared , weak pointers, boost has weak pointer exact same reason.


Comments

Popular posts from this blog

qt - Using float or double for own QML classes -

Create Outlook appointment via C# .Net -

ios - Swift Array Resetting Itself -