Reputation: 51
Is there any Memory leak in this program if yes then how to overcome this problem??
#include<iostream>
using namespace std;
class A
{
double a,b;
public:
A(double X,double Y)
{
try
{
a = X;
b = Y;
if(b==0)
throw b;
else
cout <<"Division:"<<a/b<<endl;
}
catch (double z)
{
throw z;
}
}
~A()
{
cout<<"Object Destroyed"<<endl;
}
};
int main()
{
try
{
A object(10,2);
A object1(4,2);
A object2(4,0);
}
catch(double a)
{
cout<<"Zero:"<<a<<endl;
}
return 0;
}
For Object2 why destructor is not called,and what is the best way to throw exception from constructor if there is any??
Upvotes: 0
Views: 87
Reputation: 5635
So you are not doing any dynamic allocation, it is all stack based. So it will clean up acceptably. As you are aware, your destructor is not doing anything useful.
But note that throw in a constructor does not call the corresponding destructor, and if that constructor for object2 /had/ done any allocation (that you wanted to clean up in the destructor) before it threw then it could very easily leak. But note that members with constructors and base classes to get destructed. The rule is that for every subobject whose construction was /completed/ the corresponding destructor will get called, but by throwing in the middle of this constructor function, then it did not complete, and its corresponding destructor is not called.
This is the difficulty of using throw
in constructors - and the need to either bullet-proof everything with RAII buffers or clean up in the catch.
There is more info here about what does and does not get destructed: What destructors are run when the constructor throws an exception?
Upvotes: 1