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

  • A+
Category:Languages

I was reading this article by Herb Sutter about passing smart pointers to functions. He doesn't mention std::weak_ptr and honestly I can't find a good scenario where passing such smart pointer is useful.

Does the function take ownership? Pass std::shared_ptr. Does the function just need to operate on the underlying object? Pass a raw pointer or a reference.

So is passing std::weak_ptr to functions 100% useless?

 


So is passing std::weak_ptr to functions 100% useless?

No.

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.

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: