Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When to use boost::optional and when to use std::unique_ptr in cases when you want to implement a function that can return "nothing"?

Tags:

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?

like image 304
NoSenseEtAl Avatar asked Jan 16 '13 14:01

NoSenseEtAl


People also ask

What is the use of std :: unique_ptr?

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.

What is std :: optional used for?

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.

Is unique_ptr empty?

std::unique_ptr::unique_ptrThe object is empty (owns nothing), with value-initialized stored pointer and stored deleter.

Is boost :: optional a pointer?

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.


1 Answers

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 classes
  • std::unique_ptr<Person> for polymorphic classes

because dynamic allocation incurs an overhead, so you only use it when necessary.

like image 169
Matthieu M. Avatar answered Sep 22 '22 16:09

Matthieu M.