Reputation: 585
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
Upvotes: 1
Views: 207
Reputation: 34618
No, that is exactly the point and intended use case for smart pointers and RAII in general.
Also note that your delete a
in your destructor is wrong in any case as the unique_ptr
is not a pointer itself. Relatedly, destructors are also not called if there is an exception in the constructor.
Upvotes: 1