c++boostboost-smart-ptr

how to convert a boost::weak_ptr to a boost::shared_ptr


i have a shared_ptr and a weak_ptr

typedef boost::weak_ptr<classname> classnamePtr;
typedef boost::shared_ptr<x> xPtr;

how to convert a weak_ptr to a shared_ptr

shared_ptr = weak_ptr;
Xptr = classnameptr; ?????

Solution

  • As already said

    boost::shared_ptr<Type> ptr = weak_ptr.lock(); 
    

    If you do not want an exception or simply use the cast constructor

    boost::shared_ptr<Type> ptr(weak_ptr);
    

    This will throw if the weak pointer is already deleted.