Below is my sample code. Base class has a pointer of A class with memory assigned from heap using new operator. I am explicitly throwing an exception. Since I am not invoking delete on *ptr the memory allocated by new is not released. Since the object is not constructed completely how can we release memory?
#include <iostream>
using namespace std;
class A
{
public:
A()
{
cout<<"A::ctor"<<endl;
}
~A()
{
cout<<"A::Dctor"<<endl;
}
};
class Base
{
public:
A *ptr;
Base()
{
ptr = new A();
cout<<"Base::Ctor"<<endl;
throw std::exception();
}
~Base()
{
delete ptr;
cout<<"Base::Dtor"<<endl;
}
};
int main()
{
try{
Base bobj;
}
catch(exception e)
{
cout<<e.what();
}
return 0;
}
When Base constructor throws exception the control goes to catch block and exception is handled. But how is the memory allocated by ptr = new A(); released?
Now I know using smart pointers would solve the issue. But before C++11 how were such situations handled.
In addition, I would like to know how do we close file handlers of a file handler is opened in constructor and constructor has an exception?
Base()
{
ofstream myfile;
myfile.open("myfile.txt");
..........
throw std::exception();
}
~Base()
{
myfile.close();
}
The memory associated with ptr is never released!
Yes, that was always a problem.
Prior to C++11 you could build your own smart pointer class (or use the one in Boost for example), or take care to delete prior to throwing an exception. Putting ptr in a base class is also an alternative: the base class constructor will complete before the derived constructor's function body is reached.
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