Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use for applying weak_ptr to contents of unique_ptr

I'm trying to understand the unique_ptr, shared_ptr, and weak_ptr that came in with c++11.

I've heard that weak_ptr's would be nice for things like caching, and breaking cycles, and so on. I've heard that they work well with shared_ptrs.

But in this regard, what's the difference between shared_ptrs and unique_ptrs? Why does weak_ptr only get to be used with one and not the other? Why wouldn't I want to have a weak reference to something owned by someone else?

like image 228
Verdagon Avatar asked Dec 11 '22 16:12

Verdagon


1 Answers

A weak_ptr is technically a means to hang on to the reference counter of a set of shared_ptrs that manage some shared object. When the last shared_ptr is destroyed the object is destroyed, but its reference counter lives on as long as there are weak_ptrs to it. Thus via any still exising weak_ptr you can check whether the object still exists, or has been destroyed.

If it still exists then from the weak_ptr you can obtain a shared_ptr that lets you reference the object.

The main usage of this is to break cycles.

In particular, an object can contain a weak_ptr holding on to its own reference counter, which allows you to obtain a shared_ptr to the object from the object itself. That is, a shared_ptr that uses the same reference counter as other shared_ptrs to this object. Which is how enable_shared_from_this works.

unique_ptr doesn't have any reference counter, so it doesn't make sense to hang on to that non-existent reference counter.

like image 71
Cheers and hth. - Alf Avatar answered Dec 27 '22 15:12

Cheers and hth. - Alf