lundi 13 juillet 2020

How to Overcome Memory Leak while throwing exception from constructor?

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??

Aucun commentaire:

Enregistrer un commentaire