tags:

views:

62

answers:

3

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; ?????
+1  A: 
boost::shared_ptr<Type> ptr = weak_ptr.lock(); // weak_ptr being boost::weak_ptr<Type>
reko_t
+4  A: 

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
}
Idan K
hey idan thanx for the response
Pinky
typedef boost::shared_ptr<TSmsMessage> SmsMessagePtr; inorder to avoid cyclic references im gonna change this to weak ptr how do i do it
Pinky
typedef boost::weak_ptr<classname> classnamePtr;typedef boost::shared_ptr<classname> classnameWeakPtr;
Pinky
is this the way we declare a weak_ptr
Pinky
well in your `shared_ptr` typedef there's the word `weak` so that might be misleading. but to give you a more complete answer you're gonna have to show more code and be more specific.
Idan K
typedef boost::shared_ptr<TSmsMessage> SmsMessagePtr;typedef boost::weak_ptr<TSmsMessage> SmsMessageWeakPtr; now already my code is making use of SmsMessagePtr (shared_ptr) now that to avoid cyclic references im making use of weak_ptr so shd i change al the place of shared_ptr to weak_ptr if so how to do it???
Pinky
@Idan K: actually I always found this missing that a copy constructor did not exist that would call `lock` for you. I assume they meant to remind the user of what was going on behind the scenes.
Matthieu M.
+1  A: 

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.

mkaes