Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Exception Handling Code Please explain it

Tags:

c++

exception

Please see the following code and its output - please explain me the code

void abc(int);

class A
{
public:
    A()
    {
        cout<<"Constructor Called";
    }
    ~A()
    {
        cout<<"Destructor called";
    }
};

int main()
{
    try
    {
        abc(-1);
    }
    catch(int p)
    {
        cout<<p<<endl;
    }
    return 0;
}

void abc(int p)
{
    A * Aptr = new A[2];
    if(p<0)
        throw p;
}

Output:

Constructor Called
Constructor Called
-1

can anyone explain why is the destructor not being called as in the case of normal stack unwinding

like image 876
manugupt1 Avatar asked Feb 26 '26 00:02

manugupt1


2 Answers

This pointer:

 A * Aptr = new A[2];

is a raw pointer. When it goes out of scope only the pointer itself is destroyed - nothing is done to the array it points to. So the array is not delete[]'ed and the destructors are not called. It's a typical example of a memory leak.

There're three typical solutions to the problem:

  • allocate the array itself on stack
  • use std::vector
  • use a smart pointer (not std::auto_ptr - it is not suitable for using with arrays.
like image 69
sharptooth Avatar answered Feb 27 '26 13:02

sharptooth


The destructor is not called because the objects you allocate are never deleted. You would get the same output if you removed the throw.

If, on the other hand, you changed your function into this:

void abc(int p)
{
    A A_array[2];
    if (p<0)
        throw p;
}

You would see that the destructor was called.

like image 38
Magnus Hoff Avatar answered Feb 27 '26 14:02

Magnus Hoff



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!