Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Catching exceptions in constructor

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)
    {

    }
}
like image 683
user103214 Avatar asked Oct 10 '11 07:10

user103214


Video Answer


1 Answers

Catch the exception in the constructor, tidy up (deallocate your memory), then throw the exception without the memory leak.

like image 84
Ed Heal Avatar answered Sep 25 '22 20:09

Ed Heal