get weakptr point from this

get weakptr point from this

和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";
}








你可能感兴趣的:(get weakptr point from this)