Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I get a raw pointer from boost's weak_ptr?

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?

like image 758
Czubaka Avatar asked May 17 '10 14:05

Czubaka


People also ask

How can a weak_ptr be turned into a shared_ptr?

To access the object, a weak_ptr can be converted to a shared_ptr using the shared_ptr constructor or the member function lock.

What is the use of weak_ptr in C++?

By using a weak_ptr , you can create a shared_ptr that joins to an existing set of related instances, but only if the underlying memory resource is still valid. A weak_ptr itself does not participate in the reference counting, and therefore, it cannot prevent the reference count from going to zero.

What is std :: weak_ptr?

std::weak_ptr is a smart pointer that holds a non-owning ("weak") reference to an object that is managed by std::shared_ptr. It must be converted to std::shared_ptr in order to access the referenced object.


2 Answers

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.

like image 72
James McNellis Avatar answered Sep 24 '22 14:09

James McNellis


This is an old question and the accepted answer is good, so I hesitate to post another answer, but one thing that seems missing is a good idiomatic usage example:

boost::weak_ptr<T> weak_example;
...
if (boost::shared_ptr<T> example = weak_example.lock())
{
    // do something with example; it's safe to use example.get() to get the
    // raw pointer, *only if* it's only used within this scope, not cached.
}
else
{
    // do something sensible (often nothing) if the object's already destroyed
}

A key advantage of this idiom is that the strong pointer is scoped to the if-true block, which helps to prevent accidental use of a non-initialised reference, or keeping a strong reference around longer than it is actually required.

like image 44
Miral Avatar answered Sep 23 '22 14:09

Miral