Weak_ptr

Weak_ptr

std::weak_ptr is a smart pointer that holds a non-owning ("weak") reference to an object that is managed by std::shared_ptr. It is used to break reference cycles and to void unnecessary memory retention

Reference count

A std::weak_ptr does not increase the reference count of the object it points to. Instead, it holds a reference to the std::shared_ptr that owns the object, and is notified when the object is destroyed.

This means that the object pointed to by a std::weak_ptr may be destroyed at any time, and the std::weak_ptr must be checked before dereferencing it.

#include <memory>
#include <iostream>

struct Duck
{
    Duck() { std::cout << "Duck::Duck\n"; }
    ~Duck() { std::cout << "Duck::~Duck\n"; }
    void duck() { std::cout << "Duck::duck\n"; }
};

int main()
{
    std::shared_ptr<Duck> sp1 = std::make_shared<Duck>();
    std::weak_ptr<Duck> wp1 = sp1;
    {
        // Load underlying shared_ptr from weak_ptr
        std::shared_ptr<Duck> sp2 = wp1.lock();
        if (sp2)
        {
            std::cout << " Shared ptr is Alive\n";
            sp2->duck();
        }
        else
        {
            std::cout << "Shared ptr is not Alive\n";
        }
    }
    // Let us make our shared_ptr RIP
    sp1.reset();

    // Now attempt to load shared_ptr using lock method
    std::shared_ptr<Duck> sp3 = wp1.lock();
    if (sp3)
    {
        std::cout << " Shared ptr is Alive\n";
    }
    else
    {
        std::cout << " Shared ptr is not Alive\n";
    }
    return 0;
}

Can you Guess the behavior, when the snippet is run ?

Duck::Duck
Shared ptr is Alive
Duck::duck
Duck::~Duck
Shared ptr is not Alive

Finishing note:

std::weak_ptr should not be used as a standalone object. It must always be converted to a std::shared_ptr before being used to access the object it points to.

Did you find this article valuable?

Support cppnuggets by becoming a sponsor. Any amount is appreciated!