3
#include <iostream>
#include <exception>
using std::cout;
using std::endl;
class test
{
 public:
    test()
    {
        cout<<"constructor called"<<endl;
    }
    ~test()
    {
        cout<<"destructor called"<<endl;
    }
    void fun(int x)
    {
       throw x;
    }
};

int main()
{
    try
    {
        static test k;          
        k.fun(3);
    }
    catch(int k)
    {
        cout<<"exception handler"<<endl;
    }
}

When the exception is thrown, then during the stack unwinding process, I think only local objects are destroyed, not static or heap objects. If this is true, I am not sure why the class (test) destructor is called? Thanks.

templatetypedef
  • 362,284
  • 104
  • 897
  • 1,065
Alok
  • 1,997
  • 2
  • 18
  • 30

3 Answers3

4

The test destructor is called after main exits.

    catch(int k)
    {
        cout<<"exception handler"<<endl;
    }
    // Added this line
    std::cout << "Main Exiting\n";
}

Now testing

> g++ test.cpp
> ./a.out
constructor called
exception handler
Main Exiting
destructor called

Static (static storage duration objects) are destroyed in the reverse order of creation after main exits.

Martin York
  • 257,169
  • 86
  • 333
  • 562
0

The destructor is called because your program is exiting. Only objects of automatic storage duration (that is definitely not stack objects or heap objects) are destroyed.

Puppy
  • 144,682
  • 38
  • 256
  • 465
0

When running this code, I get the output

constructor called
exception handler
destructor called

Which makes sense. The constructor for the static test object is invoked first. When the exception is thrown, it is caught by the exception handler and the message is printed. Finally, when the program terminates, the destructor for the static test object is invoked.

Exceptions only cause the lifetimes of variables with automatic duration (i.e. locals) to end, assuming that the exception is actually caught somewhere. Exceptions will not destroy objects with dynamic duration (i.e. things allocated with new), though if an exception occurs in a constructor for a dynamically-allocated object the memory will be reclaimed, since there's otherwise no way to get the memory back. Similarly, static objects are not destroyed, since they're supposed to last for the entire program. If they were cleaned up, it could cause problems if references to those objects had been passed around the program.

Hope this helps!

templatetypedef
  • 362,284
  • 104
  • 897
  • 1,065
  • yes, you are right but if exception occurs in the construtor duing the allocating of memory dynamically , then there is no need to reclaim the memory because if the constructor is not fully constructed , its not going to call delete. – Alok Jun 20 '11 at 22:10