I admit it: I'm in love with the concept of optional. The quality of my code has improved so much ever since I discovered it. Making it explicit whether a variable may or may not be valid is so much better than plain error codes and in-band signaling. It also allows me to not worry about having to read the contract in the documentation, or worrying about whether it's up-to-date: the code itself is the contract.
That said, sometimes I need to deal with std::unique_ptr
. Objects of this type might be null or not; at a given point in the code is impossible to know whether the std::unique_ptr
is supposed to have a value or not; it's impossible to know the contract from the code.
I would like to somehow mix optional
(maybe withboost::optional
) and std::unique_ptr
, so that I have a dynamically allocated object with scope-destruction and proper copy/move behaviour that explicitly states that it may not have a value. That way, I can use this new type to make it explicit that a check for value is necessary and avoid unnecessary checks for plain std::unique_ptr
.
Is there a tool for this inside the C++11 standard, boost
or a popular enough library? I could accept defining my own class for this, but that would be the least preferred method (due to lack of thorough testing).