From what I understand there are 2* ways you can implement a function that sometimes doesnt return a result(for example is person found in a list of ppl).
*- we ignore raw ptr version, pair with a bool flag, and exception when none found version.
boost::optional<Person> findPersonInList();
or
std::unique_ptr<Person> findPersonInList();
So are there any reasons to prefere one over the other?
std::unique_ptr is a smart pointer that owns and manages another object through a pointer and disposes of that object when the unique_ptr goes out of scope. The object is disposed of, using the associated deleter when either of the following happens: the managing unique_ptr object is destroyed.
We use std::optional to make our code more expressive. std::optional contains the object within itself, depending on where it is stored (stack/data/heap) std::optional makes a copy of the contained object.
std::unique_ptr::unique_ptrThe object is empty (owns nothing), with value-initialized stored pointer and stored deleter.
boost::optional appears to work like a pointer. However, you should not think of boost::optional as a pointer because, for example, values in boost::optional are copied by the copy constructor while a pointer does not copy the value it points to.
It depends: do you wish to return a handle or a copy.
If you wish to return a handle:
Person*
boost::optional<Person&>
are both acceptable choices. I tend to use a Ptr<Person>
class which throws in case of null access, but that's my paranoia.
If you wish to return a copy:
boost::optional<Person>
for non polymorphic classesstd::unique_ptr<Person>
for polymorphic classesbecause dynamic allocation incurs an overhead, so you only use it when necessary.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With