Pinky
Pinky

Reputation: 1227

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; ?????

Upvotes: 5

Views: 7717

Answers (3)

mkaes
mkaes

Reputation: 14119

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.

Upvotes: 10

Idan K
Idan K

Reputation: 20881

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
}

Upvotes: 9

reko_t
reko_t

Reputation: 56430

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

Upvotes: 2

Related Questions