为什么C ++标准库不使用虚拟继承进行异常?

时间:2016-11-20 16:52:34

标签: c++ exception inheritance

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

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])方式解决。

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

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

Q1:对于技术原因,标准库是否实现了这种行为?

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

1 个答案:

答案 0 :(得分:2)

sql_disconnected派生std::runtime_error但不从sql_exception派生std::runtime_error对我来说没有意义。恕我直言,任何SQL错误都应被视为运行时错误。 std::exception来自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) { } } ,因此您不需要首先创建钻石层次结构,因此您不需要使用虚拟继承来解决该问题。标准STL异常都不使用虚拟继承,也不应该使用自定义异常。

SQS
相关问题