Exceptions mit mehrdeutiger Basisklasse
-
Ich habe mal eine Frage, die mir den ganzen Tag schon durch den Kopf geht. Gegeben sei die folgende Hierarchie:
class A {}; class B : public A {}; class C : public A {}; class D : public B, public C {};
A ist hier ja nicht virtuell abgeleitet und kommt daher doppelt in einem D vor.
D d; A* p = &d;
führt nun verständlicherweise zu einem Fehler wegen Mehrdeutigkeit.
Was aber passiert hier bzw. sollte passieren?try { throw D(); } catch(A&) { }
Wird die Exception gefangen? Wenn ja, welches A?
-
Ich antworte mir mal selbst:
14.3 Catching Exceptions [except.catch]
Consider:
void f()
{
try {
throw E() ;
}
catch(H) {
/ / when do we get here?
}
}
The handler is invoked:
[1] If H is the same type as E.
[2] If H is an unambiguous public base of E.
[3] If H and E are pointer types and [1] or [2] holds for the types to which they refer.
[4] If H is a reference and [1] or [2] holds for the type to which H refers.
In addition, we can add const to the type used to catch an exception in the same way that we can
add it to a function parameter. This doesn’t change the set of exceptions we can catch; it only
restricts us from modifying the exception caught.[2] trifft nicht zu, denn die Basisklasse ist ja mehrdeutig. Die Exception wird also nie gefangen.