Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating weak_ptr<> from raw pointer

I'd like to wrap raw pointer member to some smart pointer to prevent deleting inside a developing class. Owner of the object under pointer is outside of class. So, looks like boost::shared_ptr and std::auto_ptr does not fit. The following is a reduced example:

class Foo {
  boost::weak_ptr<Bar> m_bar;
public:
  void setBar(const Bar *bar) { // bar created on heap
    m_bar = bar;                // naturally compilation error
  }
};

Of course, it induces compilation error. What is a correct way to initialize weak_ptr from a raw pointer (if exist)?

like image 375
Loom Avatar asked Oct 02 '13 15:10

Loom


People also ask

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.

How is weak_ptr implemented?

To implement weak_ptr , the "counter" object stores two different counters: The "use count" is the number of shared_ptr instances pointing to the object. The "weak count" is the number of weak_ptr instances pointing to the object, plus one if the "use count" is still > 0.

What is a raw pointer in C++?

A raw pointer is a pointer whose lifetime isn't controlled by an encapsulating object, such as a smart pointer. A raw pointer can be assigned the address of another non-pointer variable, or it can be assigned a value of nullptr . A pointer that hasn't been assigned a value contains random data.

What is the difference between shared_ptr and weak_ptr?

A weak_ptr is created as a copy of shared_ptr. It provides access to an object that is owned by one or more shared_ptr instances but does not participate in reference counting. The existence or destruction of weak_ptr has no effect on the shared_ptr or its other copies.


1 Answers

The only way to do it is by getting hold of a shared_ptr or weak_ptr that owns the pointer, otherwise the weak_ptr has no way to find the existing owner in order to share ownership with it.

The only way to get a shared_ptr from a raw pointer that is already owned by another shared_ptr is if Bar derives from enable_shared_from_this<Bar>, then you can do

m_bar = bar->shared_from_this();
like image 74
Jonathan Wakely Avatar answered Oct 11 '22 03:10

Jonathan Wakely