[optional] How to make boost::optional throw if trying to access uninitialized value
Hi list, I've seen in the docs that boost::optional asserts if you try to access an uninitialized value. Is it possible to make it throw an exception instead? Even in release mode? TIA
On Thu, Jul 9, 2009 at 1:13 PM,
I've seen in the docs that boost::optional asserts if you try to access an uninitialized value.
Is it possible to make it throw an exception instead? Even in release mode?
You can change BOOST_ASSERT's behavior by defining BOOST_ENABLE_ASSERT_HANDLER. See http://www.boost.org/doc/libs/1_39_0/libs/utility/assert.html for details. boost/assert.hpp can be included multiple times in a single translation unit, so if you want boost::optional to throw exceptions but other parts of Boost to still assert, you can define BOOST_ENABLE_ASSERT_HANDLER immediately before including boost/optional.hpp and undefine it immediately afterward. Josh Kelley
Josh Kelley
On Thu, Jul 9, 2009 at 1:13 PM,
wrote: I've seen in the docs that boost::optional asserts if you try to access an
uninitialized value.
Is it possible to make it throw an exception instead? Even in release mode?
You can change BOOST_ASSERT's behavior by defining BOOST_ENABLE_ASSERT_HANDLER. See http://www.boost.org/doc/libs/1_39_0/libs/utility/assert.html for details.
boost/assert.hpp can be included multiple times in a single translation unit, so if you want boost::optional to throw exceptions but other parts of Boost to still assert, you can define BOOST_ENABLE_ASSERT_HANDLER immediately before including boost/optional.hpp and undefine it immediately afterward.
Josh Kelley
Thanks for the info! I think it is not possible to have a specific boost::assertion_failed handler for boost::optional and other handlers for other assertion failures in other places, right? That would mean that the exception I throw from the handler cannot mention the fact that I am accessing an uninitialized value in a boost::optional. Maybe I should create my own my::safe_optional based on boost::optional but checking for uninitialized access. Any ideas?
participants (3)
-
dariomt
-
dariomt@gmail.com
-
Josh Kelley