posts - 23,  comments - 94,  trackbacks - 0
 1 #include <iostream>
 2 #include <boost/shared_ptr.hpp>
 3 #include <boost/enable_shared_from_this.hpp>
 4 
 5 using namespace std;
 6 
 7 class A : public boost::enable_shared_from_this<A>
 8 {
 9 public:
10     boost::shared_ptr<A> child_;
11     boost::shared_ptr<A> parent_;
12 
13     void add(boost::shared_ptr<A> child)
14     {
15         child_ = child;
16         child_->set(shared_from_this());
17     }
18 
19     void set(boost::shared_ptr<A> parent)
20     {
21         parent_ = parent;
22     }
23 };
24 
25 int main()
26 {
27     boost::shared_ptr<A> p1(new A);
28     boost::shared_ptr<A> p2(new A);
29 
30     p1->add(p2);
31 
32     cout<<p1<<endl;
33     cout<<p2<<endl;
34     cout<<p1->child_<<endl;
35     cout<<p2->parent_<<endl;
36     cout<<p1.use_count()<<endl;
37     cout<<p2.use_count()<<endl;
38 
39     return 0;
40 }

有了shared_from_this.. 我泪流满面
之前不知道这个的时候..用了很愚蠢的做法

void add(shared_ptr<A> child)
    child_ = child;
    child_->set(shared_ptr<A>(this));
}
结果错误连连~ 然后放弃使用shared_ptr... 用raw_ptr...

顺便推荐这本书
beyond_stl_cn.chm

放到了我的SVN上.. 一本很好的介绍Boost如何使用的书..

http://code.google.com/p/charlib/source/browse/trunk/Boost%20Book/Beyond_STL_cn.rar

进入页面后点右下的 view raw file 就可以下载了

以上是早上写的.. 写好后很高兴的发布了.. 但是后来发现上面这段程序非常的白痴
最关键的就在于,其实这上面的两个shared_ptr已经循环引用了.. 再也没有办法自动解开
资源也就套死在了原地.. Oh My God... 居然愚蠢到这种地步..

然后才发现.. weak_ptr 一点都不weak.. 这里就需要用weak_ptr来处理!

换成下面这个...
#include <iostream>
#include 
<boost/shared_ptr.hpp>
#include 
<boost/weak_ptr.hpp>
#include 
<boost/enable_shared_from_this.hpp>

using namespace std;

class A : public boost::enable_shared_from_this<A>
{
public:
    A(
const int id) : id_(id) { cout<<id_<<" Constructed!"<<endl; }
    
~A() { cout<<id_<<" Destructed!"<<endl; }

    
int id_;
    boost::shared_ptr
<A> child_;
    boost::weak_ptr
<A> parent_;

    
void add(boost::shared_ptr<A> child)
    {
        child_ 
= child;
        child_
->set(shared_from_this());
    }

    
void set(boost::shared_ptr<A> parent)
    {
        parent_ 
= parent;
    }

    boost::shared_ptr
<A> get_parent()
    {
        
return parent_.lock();
    }
};

int main()
{
    boost::shared_ptr
<A> p1(new A(1));
    boost::shared_ptr
<A> p2(new A(2));

    p1
->add(p2);

    
return 0;
}

通过这个测试..
输出的结果是
1 Construct
2 Construct
1 Destruct
2 Destruct

这样的输出并不奇怪. 因为 weak_ptr 是 shared_ptr 的观察者,将 shared_ptr 传给 weak_ptr 不会增加 shared_ptr的引用计数. 所以这里的操作, p2 的引用计数是2, p1 的引用计数是1, 所以p1是unique的,p1先析构,p2的引用计数-1,然后析构.

不过这里资源的析构顺序可能不是我们关心的范围,我这里认为把资源丢给智能指针这类物件管理后,主要是为了资源不泄漏,资源的析构顺序如果在关心的范围,也就该自己管理该资源了.

自己犯的一个低级错误,赶忙把帖子存草稿了. 现在弄清楚怎么处理后,才敢发上来,呵呵~ ^ ^

posted on 2009-03-12 19:20 Charlie 侯杰 阅读(8875) 评论(4)  编辑 收藏 引用

只有注册用户登录后才能发表评论。
网站导航: 博客园   IT新闻   BlogJava   知识库   博问   管理


by Charlie