Boost logo

Boost Users :

Subject: Re: [Boost-users] [optional] How to make boost::optional throw if trying to access uninitialized value
From: Anders Dalvander (boost_at_[hidden])
Date: 2009-07-10 10:00:52


dariomt_at_[hidden] 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 list run by williamkempf at hotmail.com, kalb at libertysoft.com, bjorn.karlsson at readsoft.com, gregod at cs.rpi.edu, wekempf at cox.net