uuu777
uuu777

Reputation: 901

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.

Upvotes: 0

Views: 53

Answers (2)

ravi
ravi

Reputation: 10733

I don't know why you're insisting on returning shared_ptr? shared_ptr are tools for managing memory. You can use these inside your function. However it won't make any difference to caller of your function whether you are returning a shared_ptr, reference/raw-pointer.( In an asynchronous context, there are many pitfalls ).

Also, shared_ptr's are based on reference counting mechanism i.e they are deleted only when it is no longer referenced by anyone. So, if you are returning it you have to make sure you are not storing it permanently which would never enable it's reference count to reach 0.

Upvotes: 0

John Zwinck
John Zwinck

Reputation: 249123

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
}

Upvotes: 3

Related Questions