How to check if weak_ptr is empty (non-assigned)?

You can use two calls to owner_before to check equality with a default constructed (empty) weak pointer: template <typename T> bool is_uninitialized(std::weak_ptr<T> const& weak) { using wt = std::weak_ptr<T>; return !weak.owner_before(wt{}) && !wt{}.owner_before(weak); } This will only return true if w{} “==” weak, where “==” compares owner, and according to en.cppreference.com: The order is such … Read more

How can you efficiently check whether two std::weak_ptr pointers are pointing to the same object?

Completely rewriting this answer because I totally misunderstood. This is a tricky thing to get right! The usual implementation of std::weak_ptr and std::shared_ptr that is consistent with the standard is to have two heap objects: the managed object, and a control block. Each shared pointer that refers to the same object contains a pointer to … Read more

Equality-compare std::weak_ptr

Completely rewriting this answer because I totally misunderstood. This is a tricky thing to get right! The usual implementation of std::weak_ptr and std::shared_ptr that is consistent with the standard is to have two heap objects: the managed object, and a control block. Each shared pointer that refers to the same object contains a pointer to … Read more

boost, shared ptr Vs weak ptr? Which to use when?

In general and summary, Strong pointers guarantee their own validity. Use them, for example, when: You own the object being pointed at; you create it and destroy it You do not have defined behavior if the object doesn’t exist You need to enforce that the object exists. Weak pointers guarantee knowing their own validity. Use … Read more

How does weak_ptr work?

shared_ptr uses an extra “counter” object (aka. “shared count” or “control block”) to store the reference count. (BTW: that “counter” object also stores the deleter.) Every shared_ptr and weak_ptr contains a pointer to the actual pointee, and a second pointer to the “counter” object. To implement weak_ptr, the “counter” object stores two different counters: The … Read more

Why can’t a weak_ptr be constructed from a unique_ptr?

If you think about it, a weak_ptr must refer to something other than the object itself. That’s because the object can cease to exist (when there are no more strong pointers to it) and the weak_ptr still has to refer to something that contains the information that the object no longer exists. With a shared_ptr, … Read more