I came across a situation where constructor allocated the dynamic memory and if any exception occurs in the constructor, it was not freeing the dynamically allocated memory. To avoid such situation I used unique_ptr, and it is able to free the memory properly.
To showcase the situation here is a dummy code for that.
class ExceptionInConstructor
{
unique_ptr<int> a;
public:
ExceptionInConstructor()
{
a = std::unique_ptr<int>( new int(10));
cout <<"Constructor called. Value of a is "<< *a<<endl;
//some exception occurs after the mrmory allocation
throw exception();
}
~ExceptionInConstructor()
{
cout << "Dest called()"<<endl;
}
};
int main()
{
try
{
ExceptionInConstructor ex;
}
catch(...)
{}
return 0;
}
Is it a correct and efficient way for such a situation or is there any better option for such a scenario?
Edit 1: Removed the commented code in destructor which was left by mistake