Obviously, std::optional
is the best choice to return an optional value from a function if one uses C++17 or boost (see also GOTW #90)
std::optional<double> possiblyFailingCalculation()
But what and why would be the best alternative if one is stuck with an older version (and can't use boost)?
I see a few options:
STL smart pointers (C++11 only)
std::unique_ptr<double> possiblyFailingCalculation();
Pairing it up with a bool
std::pair<double,bool> possiblyFailingCalculation();
Old style
bool possiblyFailingCalculation(double& output);
auto value = calculation()
styleA DIY template: a basic template with the same functionality is easy enough to code, but are there any pitfalls to implement a robust std::optional<T>
look-a-like template ?
Throw an exception
The class template std::optional manages an optional contained value, i.e. a value that may or may not be present. A common use case for optional is the return value of a function that may fail.
In a main function, the return statement and expression are optional. What happens to the returned value, if one is specified, depends on the implementation. Microsoft-specific: The Microsoft C implementation returns the expression value to the process that invoked the program, such as cmd.exe .
As a conclusion, std::optional is as efficient as a custom type to represent an optional integer value. Don't implement your own type, simply use the standard type.
Boost C++ Libraries Class template optional is a wrapper for representing 'optional' (or 'nullable') objects who may not (yet) contain a valid value. Optional objects offer full value semantics; they are good for passing by value and usage inside STL containers.
std::optional
, like its boost::optional
parent, is a pretty basic class template. It's a bool
, some storage, and a bunch of convenience member functions most of which are one line of code and an assert.
The DIY option is definitely preferred. (1) involves allocation and (2), (3) involve having to construct a T
even if you want a null value - which doesn't matter at all for double
but does matter for more expensive types. With (5), exceptions are not a replacement for optional
.
You can always compare your implementation to Boost's. It's a small header-only library, after all.
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