c++boostboost-optional

boost::optional vs boost::make_optional


I would like to understand better the difference between creating a boost::optional object using the default constructor:

boost::optional<PastaType> pasta = boost::optional<PastaType>(spaghetti)

or using the make_optional version:

boost::optional<PastaType> pasta = boost::make_optional<PastaType>(spaghetti)

Looking around I just understoood that with the make_optional version PastaType cannot be a reference type, but I would like to figure out better when to use one or the other.

Thanks!


Solution

  • make_optional is a convenience or helper function that can reduce the amount of code you have to write by inferring the template parameter of optional. Functionally the two methods are equivalent.

    auto pasta = boost::make_optional(spaghetti);