I think there is memory leak as B constructor not called. What is best way to handle exception in constructor if that constructor allocates objects of other class and if at some point exception occurs it need to free all previously allocated objects or is there is way to manage this automatically.
#include <iostream>
#include<utility>
using namespace std;
class A
{
private:
int *eleA;
public:
A()
{
eleA = new int;
//*eleA = 0;
cout<<"Constructor A\n";
}
~A()
{
cout<<"Destructor A \n";
delete eleA;
eleA = nullptr;
}
};
class B
{
private:
int *eleB;
public:
B()
{
cout<<"Constructor B\n";
eleB = new int;
//*eleB = 0;
throw -1; //Exception thrown
}
~B()
{
cout<<"Destructor B \n";
delete eleB;
eleB = nullptr;
}
};
class AB
{
private:
A *a_ptr;
B *b_ptr;
public:
AB() : a_ptr(nullptr),b_ptr(nullptr)
{
try{
cout<<"Constructor AB \n";
a_ptr = new A;
b_ptr = new B;
}
catch(int a)
{
cout<<"Exception catched\n";
}
}
~AB()
{
cout<<"Destructor AB \n";
if (a_ptr)
{
delete a_ptr;
a_ptr = nullptr;
}
if (b_ptr)
{
delete b_ptr;
b_ptr = nullptr;
}
}
};
int main()
{
AB *ab = new AB;
delete ab;
return 0;
}
Output:
Constructor AB
Constructor A
Constructor B
Exception catched
Destructor AB
Destructor A
Aucun commentaire:
Enregistrer un commentaire