Search code examples
c++shared-ptr

found/not-found indication with shared_ptr


I routinely use following primitive elements in some internal tables.

X const* find(Key const& key);

If found return pointer to found element if not found return null.

I would like to do something similar with shared_ptr instead of naked pointer.


Solution

  • No problem, it works the same way more or less. shared_ptr has a default constructor which makes a "null" pointer, and it also has an operator which lets you evaluate the shared_ptr in a boolean context like an if conndition. So when you have nothing to return, just say:

    return shared_ptr<X>();
    

    And to test it:

    if (shared_ptr<X> ptr = myFunc()) {
      // do something with *ptr
    }