c++exceptionobject-destruction

Are static objects deleted when an exception is thrown, or just local objects?


#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.


Solution

  • 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.