views:

241

answers:

2

Is it possible to get a raw pointer from boost::weak_ptr? Boost's shared_ptr has get() method and "->" operator. Is there some rationale behind weak_ptr not having the same functionality?

+9  A: 

A weak_ptr holds a non-owning reference, so the object to which it refers may not exist anymore. It would be inherently dangerous to use a raw pointer held by a weak_ptr.

The correct approach is to promote the weak_ptr to a shared_ptr using weak_ptr::lock() and get the pointer from that.

The Boost weak_ptr documentation explains why it would be unsafe to provide get() functionality as part of weak_ptr, and has examples of code that can cause problems.

James McNellis
For that matter, you can be left with a dangling pointer if you get a raw pointer for a `shared_ptr` that's destroyed afterwards too... in case of Multithread you can even be left with a dangling pointer in the run of the code `if (!weak.expired()) weak->run();` as the object pointed to could be destroyed between the test and the execution of the method (I suppose the method itself is properly synchronized)...
Matthieu M.
@Matthieu: of course you *can*, just as you can be left with a dangling pointer if you explicitly `delete` an object but keep a pointer to it. The point with having to promote a `weak_ptr` to `shared_ptr` is that it encourages you to correctly scope the use of the raw pointer, following the rules you normally use for `shared_ptr::get`. There would be no equivalent way to correctly scope the use of a raw pointer obtained directly from a `weak_ptr`.
Steve Jessop
+1  A: 

You first need to derive the shared_ptr from the weak_ptr before getting hold of the raw pointer.

You can call lock to get the shared_ptr, or the shared_ptr constructor:

boost::weak_ptr<int> example;
...

int* raw = boost::shared_ptr<int>(example).get();
Alan
As written, this isn't safe - you could be left with a dangling pointer if the object is deleted when the temporary `shared_ptr` is destroyed. You should keep hold of the `shared_ptr` for as long as you're using the raw pointer.
Mike Seymour