views:

306

answers:

1

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.

Thanks, Dan

A: 

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?

Kornel Kisielewicz
That would kind of defeat the purpose of allowing optional return values, which is what I am looking for... As seen in the examples:http://www.boost.org/doc/libs/1_41_0/libs/optional/doc/html/boost_optional/examples.html#boost_optional.examples.optional_return_values
Danra
@Danra -- you explicitly stated that you want an exception if the value is not present -- hence why not throw it in the function, where it's more logical to do it, than wait for it to be dereferenced?
Kornel Kisielewicz
It works for returning optional values very well. You ask it if it returned a value, and then act accordingly. Exceptions should never be a tool for normal program flow.
Kornel Kisielewicz
You convinced me :)
Danra