4

Inside a try block, a function "fun()" is invoked. A local object of class "abc" is created inside "fun" and an exception is thrown. This local object is catched in "catch" block, and this has printed a proper value. As this object was created locally, shouldn't it have printed "0(default value)" as the stack unwinding would have happened when throw was called.

#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;
}

Output : inside try
inside fun()
inside abc : 10

My expectation: inside try
inside fun()
inside abc : 0

  • 1
    The same that way `return obj` would work when returning from a function unwinds the stack. – jamesdlin Aug 27 '19 at 15:48
  • 1
    Not quite a complete duplicate, but there is a [good explanation](https://stackoverflow.com/questions/53412425/throw-temporary-instead-of-local-variable-why) of what happens when you throw an exception. – 1201ProgramAlarm Aug 27 '19 at 15:51

1 Answers1

12

A copy of the object is thrown.

Jesper Juhl
  • 30,449
  • 3
  • 47
  • 70
  • 2
    Literally the first step of the [explanation](https://en.cppreference.com/w/cpp/language/throw) is _First, copy-initializes the exception object ..._ – Useless Aug 27 '19 at 16:56