gpt4 book ai didi

c++ - std::runtime_error::runtime_error(const std::string&) 如何满足 std::exception 对 throw() 的要求?

转载 作者:IT老高 更新时间:2023-10-28 22:14:09 30 4
gpt4 key购买 nike

std::exception 要求其构造函数是 throw()。然而 std::runtime_error 接受一个 std::string 作为它的参数,这表明它在某处存储了一个 std::string。因此,必须在某处进行分配或复制构造。对于 std::string,这不是 nothrow 操作。

那么 runtime_error::runtime_error 是如何满足 throw() 的呢?

(对于上下文,我正在实现一个异常类型,并且想从调用站点存储一些 std::strings,我想正确地做到这一点......)

最佳答案

(Here's 在极简测试用例中同样的事情。)


runtime_error::runtime_error(string const&) 不需要满足 throw()

它不会继承或覆盖 exception::exception(),当 string 的复制构造函数被调用时,exception::exception() 已完成。

如果复制 string 会引发异常,这将展开 runtime_error::runtime_error(string const&) 然后,我想,调用 exception: :~exception().


很难直接表明派生 ctor 不需要满足基 ctor 的异常说明符,但以下段落强烈暗示了这一点(描述了如何调用基的析构函数,而不是将异常传递给基础构造函数):

[2003: 15.2/2] An object that is partially constructed or partially destroyed will have destructors executed for all of its fully constructed subobjects, that is, for subobjects for which the constructor has completed execution and the destructor has not yet begun execution. Should a constructor for an element of an automatic array throw an exception, only the constructed elements of that array will be destroyed. If the object or array was allocated in a new-expression, the matching deallocation function (3.7.3.2, 5.3.4, 12.5), if any, is called to free the storage occupied by the object.

唯一与您假设的(我最初假设的)情景更接近的段落如下。

[2003: 15.4/3] If a virtual function has an exception-specification, all declarations, including the definition, of any function that overrides that virtual function in any derived class shall only allow exceptions that are allowed by the exception-specification of the base class virtual function.

但显然 exception::exception() 不是虚函数,而且显然 runtime_error::runtime_error(string const&) 不会覆盖它。

(请注意,这种情况适用于虚拟析构函数;因此,you can see that, in libstdc++, runtime_error::~runtime_error() is throw())。

关于c++ - std::runtime_error::runtime_error(const std::string&) 如何满足 std::exception 对 throw() 的要求?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6864011/

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