shared_ptr weak_ptr boost 内存管理

 1 #include <string>
 2 #include <iostream>
 3 #include <boost/shared_ptr.hpp>
 4 #include <boost/weak_ptr.hpp>
 5 
 6 class parent;
 7 class children;
 8 
 9 typedef boost::shared_ptr<parent> parent_ptr;
10 typedef boost::shared_ptr<children> children_ptr;
11 
12 class parent
13 {
14 public:
15     ~parent() { std::cout <<"destroying parent\n"; }
16 
17 public:
18     children_ptr children;
19 };
20 
21 class children
22 {
23 public:
24     ~children() { std::cout <<"destroying children\n"; }
25 
26 public:
27     parent_ptr parent;
28 };
29 
30 
31 void test()
32 {
33     parent_ptr father(new parent());
34     children_ptr son(new children);
35 
36     father->children = son;
37     son->parent = father;
38 }
39 
40 void main()
41 {
42     std::cout<<"begin test...\n";
43     test();
44     std::cin.get();
45     std::cout<<"end test.\n";
46 }

输出 begin test...

递归析构, 不停

解决: weak_ptr 化 两个强引用为 其中之一为弱引用

weak_ptr是为配合shared_ptr而引入的一种智能指针来协助shared_ptr工作,它可以从一个shared_ptr或另一个weak_ptr对象构造,它的构造和析构不会引起引用记数的增加或减少。没有重载*和->但可以使用lock获得一个可用的shared_ptr对象
weak_ptr的一个重要用途是通过lock获得this指针的shared_ptr,使对象自己能够生产shared_ptr来管理自己,但助手类enable_shared_from_this的shared_from_this会返回this的shared_ptr,只需要让想被shared_ptr管理的类从它继承即可
 
#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:
    boost::weak_ptr<parent> parent;
};


void test()
{
    parent_ptr father(new parent());
    children_ptr son(new children);

    father->children = son;
    son->parent = father;
}

void main()
{
    std::cout<<"begin test...\n";
    test();
    std::cin.get();
    std::cout<<"end test.\n";
}
原文地址:https://www.cnblogs.com/threef/p/2985270.html