vendredi 25 janvier 2019

Once a lock on std::weak_ptr has returned nullptr, can it ever be non-null again?

If you take a lock on std::weak_ptr:

    class foo {};

    auto s = std::make_shared<foo>();

    std::weak_ptr<foo> w{ s };

    s = nullptr;

    s.reset(new foo());

    auto l = w.lock(); // try to get previous foo

    std::cout << "locked: " << (l != nullptr) << std::endl;

Output:

locked: 0

Once lock returns nullptr, is there every a condition under which it could return non-null, or is it effectively dead?

My test program suggests once the originally allocated object's reference count is zero then no, weak_ptr will always return a nullptr.

Aucun commentaire:

Enregistrer un commentaire