简体   繁体   中英

How to free resources when initializing list throws exception in c++?

In below code I don't see A or C's destructor called. I know I can use smart pointers etc, but in general how should we handle already allocated resources when an initializing list throws?


#include <iostream>

using namespace std;

class C
{
public:
  ~C ()
  {
    cout << "destructing C" << endl;
  }
};

class A
{
public:
  A ()
  {
    throw bad_alloc ();
  }
   ~A ()
  {
    cout << "destructing A";
  }
};

class B
{
public:
  B () try:pc (new C ()), pa (new A ())
  {
  }
  catch (...)
  {
    cout << "bad thing happened" << endl;
    throw;
  }


  A *pa;
  C *pc;
};

int
main ()
{
  try
  {
    B b;
  } catch ( ...)
  {
    cout << "i'm catching this bad here" << endl;
  }
  cout << "Hello World" << endl;

  return 0;
}

Is it guaranteed to have a leak? If so is the best practice to allocate in constructor body and then do delete in the exception handler there?

Best practice would be to use smart pointers as you suggest in your question. For example: std::unique_ptr and std::make_unique .

class B {
 public:
  B() : pc(std::make_unique<C>()), pa(std::make_unique<A>()) {}

  std::unique_ptr<C> pc;
  std::unique_ptr<A> pa;
};

In this code, if pa throws, the destructor for pc would still be called.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM