Does the constructor end up throwing an exception? Is there a memory leak?

I have followed this article and it installs

Note: if the constructor ends up throwing an exception, the memory associated with the object itself is cleared - no memory leaked. For example:

void f()
{
X x; // If X::X() throws, the memory for x itself will not leak
Y* p = new Y(); // If Y::Y() throws, the memory for *p itself will not leak
}

      

I am having a hard time understanding this and would appreciate it if someone could clarify this. I tried the following example which shows that throwing an exception inside the constructor will not trigger the destructor.

struct someObject
{
    someObject()
    {
      f = new foo();    
      throw 12;
    }
    ~someObject()
    {
        std::cout << "Destructor of someobject called";
    }

    foo* f;
};

class foo
{
public:
    foo()
    {
            g = new glue();
            someObject a;
    }
    ~foo()
    {
        std::cout << "Destructor of foo";
    }
 private:
  glue* g;
};


int main()
{
    try
    {
        foo a;
    }
    catch(int a)
    {
        //Exception caught. foo destructor not called and someobject destrucotr not called.
       //Memory leak of glue and foo objects
    }
}

      

How can I fix this problem?

Sorry for the inconvenience this update may have caused.

+3


source to share


2 answers


"... the destructor will not be called."

Since the object is not yet considered constructed, after the constructor has completed with an exception, the destructor will not be called.

Object placement and construction (just destruction) are two different things.



Any objects allocated with new()

before the exception was thrown will leak.

You don't have to manage these resources yourself, unless you really need them and are 100% sure what you are doing.

Rather, use appropriate smart pointers for class members from the standard heap management library .

+3


source


When the constructor throws, the destructor will not be called. When an exception is thrown inside a constructor, there are several things you must take into account when handling allocation resources correctly, which could have happened when the Object was interrupted:



  • the destructor for the object to be created will not be called.
  • destructors for member objects contained in this object class will be called
  • the memory for the object that is being built will be freed.
+3


source







All Articles