【发布时间】:2021-07-25 07:02:58
【问题描述】:
在下面的代码中,我没有看到 A 或 C 的析构函数被调用。我知道我可以使用智能指针等,但一般来说,当初始化列表抛出时,我们应该如何处理已经分配的资源?
#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;
}
是否保证有泄漏?如果是这样,最好在构造函数主体中分配,然后在异常处理程序中删除?
【问题讨论】:
-
你需要在
B中添加析构函数 -
@AlanBirtles:在这个问题的上下文中,由于预期构造函数会抛出异常,因此仍不会调用析构函数(即使它已显式定义)。