gpt4 book ai didi

c++ - boost::exception 和 std::exception 之间的关系

转载 作者:塔克拉玛干 更新时间:2023-11-03 01:36:08 25 4
gpt4 key购买 nike

假设有如下代码:

try {
// Do some boost stuff here
}
catch (const std::exception & stdEx) {
cout << stdEx.what() << endl;
}

问题:

1) 我知道代码适用于某些 boost 异常,即使 std::exception 和 boost::exception 不在同一个继承路径上。为什么它会起作用?

2) 它是否适用于所有 boost 异常?换句话说,是否有可以触发低于 std::exception 处理程序的 boost::exception 处理程序的示例?

最佳答案

如您所说,boost::exception 不是从 std::exception 派生的。原因查看对应的FAQ :

Despite that virtual inheritance should be used in deriving from base exception types, quite often exception types (including the ones defined in the standard library) don't derive from std::exception virtually.

If boost::exception derives from std::exception, using the enable_error_info function with such user-defined types would introduce dangerous ambiguity which would break all catch(std::exception &) statements.

Of course, boost::exception should not be used to replace std::exception as a base type in exception type hierarchies. Instead, it should be included as a virtual base, in addition to std::exception (which should probably also be derived virtually.)

recommendation是让特定的 boost 异常类(实际上)从 boost::exceptionstd::exception 派生,而不仅仅是从 boost::exception.

一些 boost 库的异常仅来自 std::exception(如 boost::bad_lexical_cast ),有些来自两者(如 boost::xpressive::regex_error )。不过,我不知道仅从 boost::exception 派生的一个,所以我想说只捕获 std::exception 应该捕获所有。

关于c++ - boost::exception 和 std::exception 之间的关系,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26998733/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com