为什么C ++标准库不使用虚拟继承进行异常? [英] Why does the C++ standard library not use virtual inheritance for exceptions?

查看:104
本文介绍了为什么C ++标准库不使用虚拟继承进行异常?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

C ++标准库定义了std :: runtime_error,类似于从std :: exception继承,但继承不是虚拟的。这使异常层次结构的扩展变得复杂。例如,以下代码有问题。

The C++ standard library defines std::runtime_error and similar to inherit from std::exception, but the inheritance is not virtual. This complicates the extension 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没有被捕获,因为它应该是恕我直言。这可以通过各种(不必要的复杂[IMHO])方式解决。

std::exception is being not caught, as IMHO it should be. This can be worked around in various (needlessly complicated [IMHO]) ways.

我认为标准应该允许这种行为,因为它不是我必须假设有一个很好的理由,除了这是标准,因为它是标准。

I believe the standard should permit this behavior, and since it doesn't I have to assume there is a good reason, other than "this is the standard because it is the standard".

我知道虚拟继承有一些成本,但AFAIK与堆栈展开和其余异常处理的成本相比,它可以忽略不计。

I am aware that there is some cost associated with virtual inheritance, but AFAIK it's negligible compared to the cost of stack unwinding and the rest of the exception handling.

Q1:对于技术原因做了标准库的实现这种行为?

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

Q2:是否考虑了扩展层次结构的问题,如果是,那么标准对该主题的评价是什么?该标准是否阻止它或建议遵循?

Q2: Was the problem of extending the hierarchy considered, and if so what does the standard say about the topic? Does the standard discourage it or have a recommendation to follow?

推荐答案

导出<$ c $对我来说没有意义c> sql_disconnected 来自 std :: runtime_error 但不能从同一个派生 sql_exception 。恕我直言,任何SQL错误都应被视为运行时错误。 std :: runtime_error 派生自 std :: exception ,因此您无需在首先,因此您不需要使用虚拟继承来解决该问题。没有标准STL异常使用虚拟继承,也不应该使用自定义异常。

It does not make sense to me to derive sql_disconnected from std::runtime_error but not also derive sql_exception from the same. IMHO any SQL error should be treated as a runtime error. std::runtime_error derives from std::exception, so you don't need to create a diamond hierarchy in the first place, and thus you don't need to use virtual inheritance to solve that problem. None of the standard STL exceptions use virtual inheritance, neither should 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) {
  }
}

这篇关于为什么C ++标准库不使用虚拟继承进行异常?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆