samedi 13 juin 2015

Why is there a memory leak when an exception is thrown from a constructor?

I read the book C++ How to Program 8th Edition by Paul Deitel. There is a statement at p.645:

When an exception is thrown from the constructor for an object that's created in a new expression, the dynamically allocated memory for that object is released.

To verify this statement, I wrote code as follows:

#include <iostream>
#include <exception>
#include <memory>

class A{
public:
  A(){std::cout << "A is coming." << std::endl;}
  ~A(){std::cout << "A is leaving." << std::endl;}
};
class B
{
public:
  B()
  {
    std::cout << "B is coming." << std::endl;
    A b;
    throw 3;
  }
  ~B(){std::cout << "B is leaving." << std::endl;}
};

int main(void)
{
    try
    {
        std::shared_ptr<B> pi(new B);
    }
    catch(...)
    {
      std::cout << "Exception handled!" << std::endl;
    }
}

The output is:

B is coming.
A is coming.
A is leaving.
Exception handled!

This shows that B's destructor isn't invoked, which seems to conflict with the statement above.

Is my code correct to verify the statement? If not, how should I modify it? If yes, does it mean that the statement is wrong?

Aucun commentaire:

Enregistrer un commentaire