Why doesn't the standard C ++ library use virtual inheritance for exceptions?

The C ++ standard library defines std :: runtime_error and is similar to inheriting from std :: exception, but inheritance is not virtual. This complicates the expansion of the exception hierarchy. For example, the following code has problems.

class sql_exception : public virtual std::exception {...}; class sql_disconnected : public virtual std::runtime_error, public virtual sql_exception {...}; void do_something() { throw sql_disconnected(); } void call_something() { try { do_something(); } catch (const std::exception& e) { } } 

std :: exception is not caught how IMHO it should be. This can be circumvented in various ways (unnecessarily complex [IMHO]).

I believe that the standard should allow this behavior, and since it is not, I must assume that there is a good reason besides "this is the standard because it is the standard."

I know there is a certain cost associated with virtual inheritance, but AFAIK is negligible compared to the cost of expanding the stack and the rest of the exception handling.

Q1: For what technical reason did the standard library implement this behavior?

Q2: Was there a problem of expanding the hierarchy considered, and if so, what does the standard say about the topic? Does the standard discourage this or has a recommendation to follow?

+5
source share
1 answer

It makes no sense for me to sql_disconnected from std::runtime_error , but also not to sql_exception from it. IMHO any SQL error should be considered a runtime error. std::runtime_error comes from std::exception , so you donโ€™t need to create a diamond hierarchy in the first place, and therefore you donโ€™t need to use virtual inheritance to solve this problem. None of the standard STL exceptions use virtual inheritance, as well as your custom exceptions.

 class sql_exception : public std::runtime_error {...}; class sql_disconnected : public sql_exception {...}; void do_something() { throw sql_disconnected(); } void call_something() { try { do_something(); } catch (const std::exception& e) { } } 
+1
source

Source: https://habr.com/ru/post/1260041/


All Articles