gpt4 book ai didi

c++ - 无法在初始化列表中捕获

转载 作者:行者123 更新时间:2023-12-04 11:49:29 25 4
gpt4 key购买 nike

对于以下代码:

#include <iostream>

struct Str
{
Str() { throw 100; }
};

class Cla
{
public:
Cla()
try : m_mem() { }
catch(...)
{
std::cout << "Catch block is called"<< std::endl;
}
private:
Str m_mem;
};

int main()
{
Cla obj;
}
我试图在 catch 块中捕获异常。但是catch块运行后,系统仍然调用std::terminate来终止程序。我没有在catch块中重新抛出异常,你能告诉我系统崩溃的原因吗?谢谢!
这是在编译器资源管理器上的测试: https://godbolt.org/z/74sTcxrY4

最佳答案

你在自相矛盾。

I tried to catch the exception in the catch block. But after the catch block is run


如果运行 catch 块,您就成功地从初始化列表中捕获了异常。你只是对接下来发生的事情感到惊讶。
首先,让我们想想当构造函数抛出时会发生什么:对象没有被构造。对?构造函数从未完成设置,因此您不能将其用于任何事情。
int main() {
Cla obj; // member subobject constructor throw, but we caught it!
obj.print(); // but we still can't use this here, because the constructor never completed
}
因此,让您在这里吞下异常并没有真正意义。您无法处理它,因为您无法返回并重新尝试构造您的成员和基类子对象。如果您没有正确构造的对象,C++ 处理它的唯一方法是展开块作用域,否则该对象将被假定为……嗯,一个真实的对象。
因此,根据 documentation :

Every catch-clause in the function-try-block for a constructor must terminate by throwing an exception. If the control reaches the end of such handler, the current exception is automatically rethrown as if by throw;. The return statement is not allowed in any catch clause of a constructor's function-try-block.


... 等价于标准 ( draft )

The currently handled exception is rethrown if control reaches the end of a handler of the function-try-block of a constructor or destructor.Otherwise, flowing off the end of the compound-statement of a handler of a function-try-block is equivalent to flowing off the end of the compound-statement of that function (see [stmt.return])

关于c++ - 无法在初始化列表中捕获,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69270763/

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