The following example leave a possible memory leak because the destructor doesn't run for the object on which the exception is handled during its constructor is run. where do i handle this memory leak?
#include <exception>
class MyClass {
public:
MyClass()
{
c = new char[5];
throw std::runtime_error("test");
}
~MyClass ()
{
delete[] c;
}
private:
char *c;
};
int main()
{
try
{
MyClass Obj;
}
catch (std::runtime_error)
{
}
}
Catch the exception in the constructor, tidy up (deallocate your memory), then throw the exception without the memory leak.
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