Conception of exceptions in the constructor

In the following example, a memory leak may occur because the destructor does not start for the object on which the exception is being processed during its constructor. where can i deal with 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)
    {

    }
}
+5
source share
4 answers

Catch an exception in the constructor, remove (free memory), and then throw an exception without memory leak.

+6
source

You are better off using RAII , in which case the smart pointer will be specific.

Or, alternatively, you can use the Two Phased Construction strategy .

try-catch delete , , , n , , , catch, RAII , , .

boost::scoped_ptr std::tr1::scoped_ptr .

+5

throw , .

  MyClass() 
  {
     if(<condition>)
       throw std::runtime_error("test");
     c = new char[<SIZE>];
  }

- try-catch(), :

MyClass() 
  try {
    c = new char[5];
    throw std::runtime_error("test");;
  }
  catch(std::runtime_error e) {
    delete[] c;
  }

.

+4

You can catch the exception in the constructor body, perform the necessary cleanup, and then throw the exception with throw;

However, exceptions and manual memory handling do not go well together. You will be much better to use an object that automatically manages memory for the member c (eg std::string, std::vector<char>, std::unique_ptr<char[]>etc.). You really only need to explicitly manage the memory if you are writing a class similar to one of the above, the purpose of which is to take care of that memory.

+1
source

All Articles