Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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; ?????
like image 951
Pinky Avatar asked Dec 01 '22 04:12

Pinky


2 Answers

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.

like image 125
mkaes Avatar answered Dec 03 '22 17:12

mkaes


You don't convert a weak_ptr to a shared_ptr as that would defeat the whole purpose of using weak_ptr in the first place.

To obtain a shared_ptr from an instance of a weak_ptr, call lock on the weak_ptr.
Usually you would do the following:

weak_ptr<foo> wp = ...;

if (shared_ptr<foo> sp = wp.lock())
{
    // safe to use sp
}
like image 24
Idan K Avatar answered Dec 03 '22 18:12

Idan K