【发布时间】:2011-11-13 05:57:36
【问题描述】:
我在处理派生类中的构造函数异常时遇到了一些问题。当派生类构造函数抛出错误,但父类已经分配了一些对象。会调用父类的析构函数吗?
例子:
class A
{
A() { /* Allocate some stuff */ };
virtual ~A() { /* Deallocate stuff */ };
};
class B : public A
{
B()
{
/* Do some allocations */
...
/* Something bad happened here */
if (somethingBadHappened)
{
/* Deallocate B Stuff */
...
/* Throws the error */
throw Error; /* Will A destructor be called? I know B destructor won't */
};
};
~B() { /* Deallocate B Stuff */ };
}
我想知道执行以下操作是否是个好主意:
B()
{
/* Do some allocations */
...
/* Something bad happened here */
if (somethingBadHappened)
{
/* Deallocate B Stuff */
this->~B();
/* Throws the error */
throw Error; /* Will A destructor be called? I know B destructor won't */
};
};
如果不是,那么做这些事情的好方法是什么?
【问题讨论】:
-
您自己尝试过什么吗?您可以将调试消息放入各种构造函数和析构函数中,看看会发生什么。
-
显式调用析构函数不会释放为对象分配的内存。
-
@Daniel:另外,您不能在构造函数中调用自己的析构函数,因为在那个阶段您还没有活动对象。
标签: c++ exception inheritance constructor destructor