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
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:
std::vectorstd::auto_ptr - it is not suitable for using with arrays.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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With