在类的构造函数中异常处理的行为 [英] Behaviour of exception handling in constructor of a class
问题描述
我有这个程序,其中派生类的ctor抛出异常。程序只是一个示例程序,我只是想了解异常处理的概念。
I have this program where the ctor of derived class throws a exception. The program is just an example program where I am just trying to understand the concept of exception handling.
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块和第一个B的dtor应该被调用,然后A的dtor。但是上面的程序的输出是:
The expected output is that it should enters catch block of B and first B's dtor should be called and then A's dtor. But the output of above program is:
Inside catch block in B's Ctor!!
DTOR called - A!!
DTOR called - B!!
DTOR called - A!!
Exception Occurred in B!!
我的问题在这里是为什么类A的dtor调用两次,当它只进入catch块B并调用B类的dtor?
另外请告诉我这里是否犯了一些错误。
任何帮助感谢
My question here is why the dtor of class A called twice when it only enters the catch block for class B and calls the dtor of class B only?? Also please do tell if I am making some mistake here. Any help is appreciated
编辑:
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块中分配的内存是异常被抛。现在在这种情况下会有一个内存泄漏,如果我不捕获异常B类
Here I have created a char pointer in class B. Allocated memory in try block in Ctor before exception is being thrown. Now in this case will there be a memory leak if i do not catch exception for class B ??
推荐答案
code>〜A()被调用两次是因为在 B()
, A )
被完全初始化,所以当发生异常时,将自动调用〜A()
,而 B
本身尚未完全初始化,因此〜B()
将不会被调用,并且您不需要也不应该删除指针if构造函数throws,C ++将调用 delete
在这种情况下。请参阅 LIVE DEMO 。
The reason that ~A()
is called twice is because inside the body of B()
, A()
is fully initialized, so when an exception occurs, ~A()
will be called automatically, while B()
itself is not fully initialized yet, so ~B()
won't be called, and you need not and shouldn't delete the pointer if the constructor throws, C++ will call delete
for you in that case. See LIVE DEMO.
这篇关于在类的构造函数中异常处理的行为的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!