Boost logo

Boost :

Subject: [boost] [exception] virtual inheritance troubles
From: Eric Niebler (eric_at_[hidden])
Date: 2010-02-26 00:33:56


In xpressive, I'm trying to follow the recommended use of
Boost.Exception and use virtual inheritance in my exception class,
regex_error. I'm also trying to hew as closely as possible to the
standard, which says that regex_error should inherit from
std::runtime_error. However, this simple use of Boost.Exception does not
compile:

   #include <string>
   #include <exception>
   #include <boost/throw_exception.hpp>
   #include <boost/exception/exception.hpp>

   struct regex_error
     : virtual std::runtime_error
     , virtual boost::exception
   {
     explicit regex_error(std::string const& what)
       : std::runtime_error(what)
     {}
   };

   int main()
   {
     boost::throw_exception(regex_error("what"));
   }

On VC9, I get the following:

> C:\boost\org\trunk\boost/exception/exception.hpp(400) : error C2512: 'std::runtime_error::runtime_error' : no appropriate default constructor available

The trouble is that std::runtime_error does not have a default
constructor, and that boost::throw_exception doesn't simply throw the
exception passed to it; it throws an object of type of
clone_impl<regex_error>. Because of the virtual inheritance, clone_impl
needs to call std::runtime_error's directly, but it doesn't. It can't
know to do that in general.

What is the recommended practice here?

<aside>
It actually doesn't seem to be particularly useful in this case to use
virtual inheritance because std::runtime_error inherits from
std::exception non-virtually. In order to avoid the pitfall described
here <http://tinyurl.com/yb2jpns>, it seems *ever* exception type in the
hierarchy needs to use virtual inheritance, and that unfortunately is
not the case for the standard exception hierarchy.
</aside>

-- 
Eric Niebler
BoostPro Computing
http://www.boostpro.com

Boost list run by bdawes at acm.org, gregod at cs.rpi.edu, cpdaniel at pacbell.net, john at johnmaddock.co.uk