johnbakers
johnbakers

Reputation: 24771

Weak pointer to unique_ptr using get()

Simple question, just want clarification that using get() on unique_ptr is like getting a weak pointer, since it has no responsibility and could be left dangling when unique_ptr is removed.

Upvotes: 2

Views: 445

Answers (2)

Manny42
Manny42

Reputation: 648

Yes, as get() will just send you a reference on this pointer and will not grant you the ownership on this pointer. So if the pointer is deleted the "getted" resource will not be accessible, and your "getted" pointer won't have to be deleted.

Upvotes: 0

David Schwartz
David Schwartz

Reputation: 182847

Correct. If you have a regular pointer, which is what get() returns, it's your responsibility to ensure you only dereference it during the object's lifetime.

It's not really like a weak pointer though. A dangling weak pointer knows that it is dangling. A regular pointer has no idea.

Upvotes: 3

Related Questions