Search code examples
c++boost-optional

How can I make sure a boost::optional<T> object is initialized in release-build?


When trying to get the value of a boost::optional object, BOOST_ASSERT is used to make sure the object is indeed initialized.

But what I would like when dereferencing an uninitialized optional is for an exception to be thrown - is there any way to get this behaviour in a release build? If not, is there any other similar library which has this behaviour?

I would hate to use the is_initialized method each time before dereferencing the object, and I'd also like to avoid wrapping the optional class in my own class to get this behaviour.


Solution

  • Unfortunately optional doesn't give such an option. The whole point of optional is to be able to check if the value is present by using the overloaded bool operator.

    Optional was designed to allow NOT to throw exceptions in functions, but return a success/failure with the value instead.

    Maybe you should return a value always instead, and throw inside the function if it fails?