c++ - 类的构造函数中的异常处理行为

标签 c++ exception

我有一个派生类的构造函数抛出异常的程序。该程序只是一个示例程序,我只是想在其中理解异常处理的概念。

class A{
public:
   A() {}

   ~A(){std::cout << "DTOR called - A!!" << std::endl;}
};

class B : public A
{
public:
   B():A()
   {
      try
      {
         init();
      }
      catch(...)
      {
         std::cout << "Inside catch block in B's Ctor!!" << std::endl;
         throw this;
      }
   }

   void init() { throw 0;  }

   ~B() {std::cout << "DTOR called - B!!" << std::endl; }
};

int main()
{
   try{
      B *b = new B;

      std::cout << "Äfter B's ctor called in try block!!" << std::endl;
      delete b;
      std::cout << "Äfter B's dtor called in try block!!" << std::endl;
   }

   catch(B* b)
   {
      delete b;
      b = NULL;
      std::cout << "Exception Occurred in B!!" << std::endl;
   }

   catch(A* a)
   {
      delete a;
      a = NULL;
      std::cout << "Exception Occurred in A!!" << std::endl;
   }

   catch(...)
   {
      std::cout << "Exception Occured!!" << std::endl;
   }
   return EXIT_SUCCESS;
}

预期的输出是它应该进入 B 的 catch block ,首先应该调用 B 的 dtor,然后是 A 的 dtor。但是上面程序的输出是:

Inside catch block in B's Ctor!!
DTOR called - A!!
DTOR called - B!!
DTOR called - A!!
Exception Occurred in B!!

我这里的问题是为什么A类的dtor只进入B类的catch block 就调用了B类的dtor却调用了两次?? 也请告诉我是否在这里犯了一些错误。 感谢任何帮助

编辑:

class B : public A
{
public:
   B():A()
   {
      try
      {
         szName = new char[100];
         init();
      }
      catch(...)
      {
         std::cout << "Inside catch block in B's Ctor!!" << std::endl;
         throw this;
      }
   }

   void init() { throw 0;  }

   ~B()
   {
      delete szName;
      std::cout << "DTOR called - B!!" << std::endl;
   }

   char *szName;
};

在这里,我在 B 类中创建了一个 char 指针。在抛出异常之前,在 Ctor 的 try block 中分配了内存。现在在这种情况下,如果我不捕获 B 类的异常,是否会发生内存泄漏??

最佳答案

为什么要在 catch block 中放入“this”?你在做“这个”的时候已经呕吐了,你怎么能扔掉它呢?试着扔掉你抓到的东西,或者其他东西,比如“哎呀”。

关于c++ - 类的构造函数中的异常处理行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26229680/

相关文章:

python - 生成器中无法捕获的异常

JavaScript 异常对象格式

c++ - 错误 C2027 : use of undefined type 'boost::python::detail::reference_existing_object_requires_a_pointer_or_reference_return_type<R>'

c++ - 由于未对齐的内存地址,内存地址是否会被破坏?

c# - 从 C# 调用托管 C++ 时出现编译错误

c++ - 从 Canny 检测和标记端点

c++ - decltype 和 is_same 给出令人困惑的结果

java - 从 NumberFormatException 获取源字符串

c# - Activator.CreateInstance() - 找不到构造函数

android - java.net.UnknownHostException : graph. facebook.com 问题