gpt4 book ai didi

C++ c-tor 处理默认成员值构造异常?

转载 作者:行者123 更新时间:2023-11-30 03:54:30 25 4
gpt4 key购买 nike

我想在默认值构造的类成员中处理异常。像这样:

int func()
{
throw 9.0;

return 9;
}

struct T
{
T() try {
}
catch(...)
{
cout << __func__ << endl;
}
int a{func()};
} ;

这可能吗?最新的 ISO C++ 标准对此有何看法?

编辑:我实际上验证了自己它适用于大多数编译器,但它是否定义明确,我通常应该使用这个结构吗?

最佳答案

Is it possible?

是的,该异常将由函数级处理程序处理,就像成员初始化程序抛出的任何其他异常一样。请注意,在构造函数的函数尝试 block 中,异常会在处理后重新抛出。如果子对象的初始化失败,这就是您想要的,因为完整的对象无效。

And what does the latest ISO C++ standard says about it?

我还没有 C++14,但是 C++11 说:

15/4: An exception thrown during the execution of the compound-statement or, for constructors and destructors, during the initialization or destruction, respectively, of the class’s subobjects, transfers control to a handler in a function-try-block in the same way as an exception thrown during the execution of a try-block transfers control to other handlers.

并且 15.3/15 指定在这种情况下它被重新抛出。

should I normally use this construct?

可能不会——您几乎无法处理子对象初始化失败的情况,因此捕获并重新抛出异常通常没有意义。您可能希望在异常通过时报告错误。

关于C++ c-tor 处理默认成员值构造异常?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29470807/

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