Use to apply weak_ptr to unique_ptr content

I am trying to understand the unique_ptr , shared_ptr and weak_ptr that came in with C ++ 11.

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

But in this respect, what is the difference between shared_ptrs and unique_ptrs ? Why can weak_ptr be used with only one, and not with the other? Why don't I want to have a weak link to something owned by someone else?

+4
source share
3 answers

A weak_ptr is technically a means to bind to the reference counter of the shared_ptr set, which manages some shared object. When the last shared_ptr is destroyed, the object is destroyed, but its reference counter works as long as it has weak_ptr . Thus, with any remaining weak_ptr you can check if the object exists or has been destroyed.

If it still exists, then from weak_ptr you can get shared_ptr , which allows you to reference the object.

The main use of this is loop interruption.

In particular, the object may contain weak_ptr , which holds its own reference counter, which allows you to get the shared_ptr object for the object from the object itself. That is, a shared_ptr that uses the same reference counter as another shared_ptr for this object. How enable_shared_from_this works.

unique_ptr does not have any reference counter, so it makes no sense to hang on this nonexistent counter.

+7
source

The main point of a weak pointer is that you can try to make the pointer strong, owning:

 auto strongPtr = weakPtr.lock(); if (strongPtr) { // still existed, now have another reference to the resource } else { // didn't still exist } 

Pay attention to the first way: strengthening a weak pointer requires us to take responsibility for the object.

That's why it doesn't make sense with unique_ptr : the only way to make a weak pointer strong is to take the resource from another place, and for unique_ptr this would mean leaving it somewhere else with an unexpected null pointer. shared_ptr gets a pass because accepting it actually means sharing it.

+4
source

I am new to C ++ 11, so if anyone knows better, I would appreciate any corrections.

I think there would be no reason for this, otherwise you would use shared_ptr , as this will defeat the whole purpose of unique_ptr . A unique_ptr implies semantics that it has full control over the object it points to.

+2
source

All Articles