5

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; ?????
manlio
  • 18,345
  • 14
  • 76
  • 126
Pinky
  • 1,217
  • 4
  • 17
  • 27
  • did you bother to look at the [documentation](http://www.boost.org/doc/libs/1_44_0/libs/smart_ptr/weak_ptr.htm)? It's on the first page. – Sam Miller Oct 07 '10 at 13:53

3 Answers3

10

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
  • 13,781
  • 10
  • 52
  • 72
9

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
  • 20,443
  • 10
  • 63
  • 83
  • hey idan thanx for the response – Pinky Oct 07 '10 at 12:23
  • typedef boost::shared_ptr SmsMessagePtr; inorder to avoid cyclic references im gonna change this to weak ptr how do i do it – Pinky Oct 07 '10 at 12:24
  • typedef boost::weak_ptr classnamePtr; typedef boost::shared_ptr classnameWeakPtr; – Pinky Oct 07 '10 at 12:27
  • is this the way we declare a weak_ptr – Pinky Oct 07 '10 at 12:27
  • 1
    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 Oct 07 '10 at 12:29
  • typedef boost::shared_ptr SmsMessagePtr; typedef boost::weak_ptr 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 Oct 07 '10 at 12:43
  • @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. Oct 07 '10 at 13:37
2
boost::shared_ptr<Type> ptr = weak_ptr.lock(); // weak_ptr being boost::weak_ptr<Type>
reko_t
  • 55,302
  • 10
  • 87
  • 77