随笔 - 21  文章 - 0  trackbacks - 0
<2014年7月>
293012345
6789101112
13141516171819
20212223242526
272829303112
3456789

常用链接

留言簿

随笔分类

随笔档案

文章分类

搜索

  •  

最新评论

阅读排行榜

评论排行榜


和enable_shared_from_this刚好相反,http://www.cppblog.com/pizzx/archive/2014/07/02/207477.html
内部持有shared_ptr作为成员变量,生命周期和类相同,通过weak_ptr可以判断当前对象生命周期是否已经结束(可以在其他线程判断,线程安全)。




#include <iostream>
#include 
<boost/weak_ptr.hpp>
#include 
<boost/shared_ptr.hpp>
#include 
<vector>

using namespace std;
using namespace boost;

class null_deleter
{
public:
void operator()(void *)
{}

}
;


class X
{
private:

    shared_ptr
<X> this_;
    
int i_;

public:

    
explicit X(int i): this_(this, null_deleter()), i_(i)
    
{
    }


    
// repeat in all constructors (including the copy constructor!)

    X(X 
const & rhs): this_(this, null_deleter()), i_(rhs.i_)
    
{
    }


    
// do not forget to not assign this_ in the copy assignment

    X 
& operator=(X const & rhs)
    
{
            i_ 
= rhs.i_;
    }


    weak_ptr
<X> get_weak_ptr() const return this_; }
}
;

int main()
{
   vector
<weak_ptr<X> >  m_vcwptr;

    
{
     X x(
1);
    }


    
{
        shared_ptr
<X>  x(new X(1));
        m_vcwptr.push_back(x
->get_weak_ptr());
        std::cout
<<"x use count: "<<x.use_count()<<"\n";

        weak_ptr
<X>  xinscope = m_vcwptr[0];

        
if(!xinscope.lock())
           std::cout
<<"xy is already expired"<<"\n";
        
else
           std::cout
<<"xy is exist "<<"\n";
    }


    weak_ptr
<X>  xy = m_vcwptr[0];

    
if(!xy.lock())
       std::cout
<<"xy is already expired"<<"\n";
}








posted on 2014-07-06 21:11 pizzx 阅读(325) 评论(0)  编辑 收藏 引用 所属分类: c++/boost

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