Quick Q: Is it useful to pass std::weak_ptr to functions?

Quick A: yes

Recently on SO:

Is it useful to pass std::weak_ptr to functions?

Consider this toy example.

struct PointerObserver
{
    std::weak_ptr<int> held_pointer;

    void observe( std::weak_ptr<int> p )
    {
        held_pointer = std::move(p);
    }

    void report() const
    {
        if ( auto sp = held_pointer.lock() )
        {
            std::cout << "Pointer points to " << *sp << "\n";
        }
        else
        {
            std::cout << "Pointer has expired.\n";
        }
    }
};

In this example, a function observe holds state.

Its weak_ptr parameter communicates that this smart pointer is not owning, but reserves the ability to own at a later time, safely detecting if the pointer has expired.

Add a Comment

Comments are closed.

Comments (0)

There are currently no comments on this entry.