为什么当我按地址抛出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?
以下是代码:
#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块中的所有本地对象一离开就会被销毁?
你的想法是正确的。
程序的行为未定义。
我预计我的程序会崩溃
这是您犯下最大错误的地方。当行为未定义时,程序不能保证崩溃。你不能依赖这样的假设。
相关文章:
- 在函数内创建的对象的范围 - 如果在函数外部存储和访问引用,它们是否有效?
- C++,在对象内分配多个数据时,堆栈分配是否更有效? 在下面的程序中,类A_Heap的效率会更低吗?
- 在 c++ 中将对象设置为等于同一类的构造函数是否有效?
- 当表示为对象的一维向量时,有效地旋转 NxM 矩阵 (C++)
- 返回一个引用C++中另一个类对象的对象的有效方法
- 在递归函数中更有效地创建对象和对象数组?C++
- 自定义类型转换运算符在转发引用上调用时不起作用(当对象按值传递时有效)
- 有效地分配堆栈对象(由函数的值返回)到堆?
- 如果一个对象是在本地创建的,并在C++中作为异常抛出,那么本地对象如何在其范围之外有效,即在 catch 块中?
- 有没有办法自动初始化 std::shared_ptr 来保存有效对象?
- 如何检查对象有效
- 如何检查指针后面的对象是否有效或已删除?
- 列出 n 个对象的所有 k 排列的有效方法,同时满足特定标准
- 如何使用 stl 容器有效地存储对象?(即根据其字段的值进行搜索)
- 如何有效地初始化大型类的对象
- 与C++共享 Julia 对象的最有效方法是什么?
- 是否有一种有效的方法可以将一系列对象与父/子关系分类
- 什么是将对象相互连接的干净有效的方法
- C++使用 shared_ptr 安全地删除事件对象有效负载
- 在类的构造函数内创建对象有效吗