开发者

Is Virtual Inheritance necessary for Exceptions?

I understand the need for virtual inheritance when using multiple inheritance -- it solves the Dreaded Diamond Problem.

But what if I'm not using multiple inheritance? Is there a need for virtual inheritance at all?

I seem to recall hearing that it was important for exceptions (throw a derived class, catch by base class reference). But shouldn't virtual destructors be sufficient for that?

I've tried searching for the reference page I once saw on this, but I can't seem to开发者_如何学Go find it.


You're probably thinking about this Boost.Exception guideline, which I'll copy here for completeness:


Using Virtual Inheritance in Exception Types

Exception types should use virtual inheritance when deriving from other exception types. This insight is due to Andrew Koenig. Using virtual inheritance prevents ambiguity problems in the exception handler:

#include <iostream>
struct my_exc1 : std::exception { char const* what() const throw(); };
struct my_exc2 : std::exception { char const* what() const throw(); };
struct your_exc3 : my_exc1, my_exc2 {};

int
main()
    {
    try { throw your_exc3(); }
    catch(std::exception const& e) {}
    catch(...) { std::cout << "whoops!" << std::endl; }
    }

The program above outputs "whoops!" because the conversion to std::exception is ambiguous.

The overhead introduced by virtual inheritance is always negligible in the context of exception handling. Note that virtual bases are initialized directly by the constructor of the most-derived-type (the type passed to the throw statement, in case of exceptions.) However, typically this detail is of no concern when boost::exception is used, because it enables exception types to be trivial structs with no members (there's nothing to initialize.) See Exception Types as Simple Semantic Tags.


Yes if your exception classes involve multiple inheritance.


The only cost of virtual inheritance is the vtable which is not much of a cost. Using virtual inheritance means that later after people inherit from various things that the double diamond problem won't unexpectedly rear their ugly head. It just means that your class will make a good base class.


No, it isn't needed except to resolve the diamond problem. You must be imagining things!


I understand the need for virtual inheritance when using multiple inheritance -- it solves the Dreaded Diamond Problem.

But what if I'm not using multiple inheritance?

Question (mostly rhetorical): How would you know that MI won't ever be used?

Answer: You can't know that. (Until you prove you do.)

I seem to recall hearing that it was important for exceptions (throw a derived class, catch by base class reference). But shouldn't virtual destructors be sufficient for that?

Question (rhetorical): Why would a virtual destructor be necessary here?

Answer: It isn't.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜