constructor throw exception

When a construct throws an exception then; that object is not fully constructed so destructor can not be called on that object. c++ destroys only fully constructed objects
So this may leads to memory leakage.


To solve this problem we have to
1. write a cleanup function which clears all allocated memory or resource
2. write the part of constructor block which  may leads to crash in try block &
call cleanup function in catch block.

#include<iostream>
using namespace std;

class first
{
    public:
        first()
        {
            cout<<"in constructor of first"<<endl;
        }
        ~first()
        {
            cout<<"in destructor of first"<<endl;
        }
};

class second
{
    first *ptr;
    first *ptr1;
    public:
        second()
        {
            cout<<"in constructor of second"<<endl;
            try {
                ptr = new first();
                throw 1;
                ptr1 = new first();
            }
            catch(...)
            {
                cleanup();
                cout<<"AFTER"<<endl;
            }

        }
        ~second()
        {
            cout<<"in destructor of second"<<endl;
            cleanup();
        }
        void cleanup()
        {
            delete ptr;
            delete ptr1;
            ptr = ptr1 = NULL;
        }
};

int main()
{
    second s;
    return 0;
}

Comments

Popular posts from this blog

STL Questions

Producer Consumer problem using mutex

Interview questions