c++ - 如果一个对象在本地创建并在 C++ 中作为异常抛出,那么本地对象如何在其范围之外有效,即在 catch block 中?

标签 c++ c++11 exception stack-unwinding

在 try block 中,调用函数“fun()”。在“fun”中创建了类“abc”的本地对象并抛出异常。这个本地对象被捕获在“catch” block 中,并且打印了一个正确的值。由于这个对象是在本地创建的,它不应该打印“0(默认值)”,因为调用 throw 时会发生堆栈展开。

#include <iostream>

using namespace std;

class abc
{
    int var;
    public:
    abc():abc(0){}
    abc(int i):var(i){}
    void print()
    {
        cout << "inside abc : " << var << endl;
    }
};

void fun()
{
    cout << "inside fun()" << endl;
    abc obj(10);
    throw obj;
}

int main()
{
    try
    {
        cout << "inside try" << endl;
        fun();
    }catch(abc& ob)
    {
        ob.print();
    }
    return 0;
}

输出: 里面试试
内部乐趣()
里面 abc : 10

我的期望: 里面试试
内部乐趣()
内 abc : 0

最佳答案

关于c++ - 如果一个对象在本地创建并在 C++ 中作为异常抛出,那么本地对象如何在其范围之外有效,即在 catch block 中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57678199/

相关文章:

c++ - c++什么时候需要用#include

c++ - 如何像普通 C 函数一样使用正确的 'this' 指针调用 C++ 类成员函数? (指向类成员函数的指针)

javascript - 未捕获的类型错误 : Cannot read property 'prototype' of null using Openerp 7. 0

java - 使用 Selenium 和 SerenityBDD (修昔底德) 进行异常和错误处理的最佳实践

c++ - C 函数参数中的数组语法与指针语法

c++ - 未为使用默认模板参数声明的别名模板指定模板参数时出错

c++ - 推送和弹出的不同互斥量

c++ - "sizeof new int;"是未定义的行为吗?

c++ - 使用非常量值初始化的对 const 类成员的引用

java - 在swing程序中使用printStackTrace()好不好?