I know auto_ptr destruct object automatically when it is out of scope. But when Constructor throws exception, it does not destruct object(take a look at below code snippet).
Let me explain below code , I have class A which has an auto_ptr field "autoPtr" (which has a pointer to Test class). In below scenario, A class constructor throws "Malloc" error. I am expecting Auto_Ptr to call Test class destructor but it does not.
#include <iostream>
#include <memory>
using namespace std;
class Test
{
public:
Test()
{
cout << "Test Constructor" << endl;
}
~Test()
{
cout << "Test Destructor" << endl;
}
};
class A
{
private:
int *ptr;
auto_ptr<Test> autoPtr;
public:
A():autoPtr(new Test()), ptr(NULL)
{
ptr = (int *)malloc(INT_MAX);
if(ptr == NULL)
throw exception("Malloc failed");
}
};
int main()
{
try
{
A *obj = new A();
}
catch (exception e)
{
cout << "Caught exception :" <<e.what()<< endl;
}
}
Output is :
Test Constructor
Caught exception :Malloc failed
Why Test class destructor was not called in the above code ?
Also Who frees A class object (obj) memory ?