std::weak_ptr::lock and object destruction

Viewed 372

I know that in a multi-threading environment it's not safe to check whether an object has been fully deleted by std::shared_ptr<T>::use_count() == 0, because the object's destructor may still be not completed.

But what about using std::weak_ptr::lock() instead?

if (weak_ptr.lock() == nullptr) {
    // The object's destructor is guaranteed to be completed?
}
1 Answers

The following should all be equivalent:

weak_ptr.use_count() == 0
weak_ptr.lock() == nullptr
weak_ptr.expired()

They share the interpretation that the last managing shared_ptr has begun its destruction. They do not imply that the managed object has yet begun its destruction, nor that it has completed its destruction.

Related