为什么当我按地址抛出try块中的本地自动对象时,该对象在catch块中仍然有效

Why is a local automatic object from a try block still alive in the catch block when I throw that object by address?

本文关键字:对象 有效 catch 地址 为什么 try      更新时间:2024-09-26

以下是代码:

#include <iostream>
using namespace std;
class A {
public:
void print() {
cout << "Object is still alive" << endl;
}
};
int main() {
try {
A a1 = A();
A* a = &a1;
throw a;
}
catch (A* a) {
a->print();
}
}

为什么对象a1在catch块中仍然有效(您可以自己检查,print方法有效(,尽管我已经向A类对象抛出了类型指针的异常?我以为try块中的所有本地对象一离开就会被销毁?

为什么捕获块中的对象a1仍然存在

它已不存在。

您可以自己检查,打印方法工作

这并不能证明对象的生存期。

我以为try块中的所有本地对象一离开就会被销毁?

你的想法是正确的。


程序的行为未定义。

我预计我的程序会崩溃

这是您犯下最大错误的地方。当行为未定义时,程序不能保证崩溃。你不能依赖这样的假设。