« Return to Thread: [optional] How to make boost::optional throw if trying to access uninitialized value

Re: [optional] How to make boost::optional throw if trying to access uninitialized value

by Anders Dalvander-3 :: Rate this Message:

Reply to Author | View in Thread

dariomt@... wrote:

> 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?
>  
You could create your own functions for this:

template <typename T>
T const& safe_get(boost::optional<T> const& opt)
{
   if (!opt)
      throw some_exception();
   return *opt;
}

template <typename T>
T& safe_get(boost::optional<T>& opt)
{
   if (!opt)
      throw some_exception();
   return *opt;
}

Regards,
Anders Dalvander

_______________________________________________
Boost-users mailing list
Boost-users@...
http://lists.boost.org/mailman/listinfo.cgi/boost-users

 « Return to Thread: [optional] How to make boost::optional throw if trying to access uninitialized value