【发布时间】:2019-10-03 13:32:42
【问题描述】:
我试图了解当构造函数抛出异常时会出现什么问题。
例如这段代码的一部分:
#include <iostream>
class X
{
public:
X(int);
~X();
private:
int* m;
};
X::X(int y)
{
m = new int(y);
throw std::exception();
}
X::~X()
{
delete m;
std::cout << "Destructor" << std::endl;
}
//---------------------------------------
int main()
{
try
{
X a(4);
}
catch (const std::exception&)
{
std::cout << "ex" << std::endl;
}
system("pause");
// output
/* ex
Press any key to continue . . .
*/
}
没有调用析构函数,所以这是内存泄漏!
1) 不使用任何智能指针是否可以解决这个问题?
2) 我的主要问题是当构造函数抛出异常时会出现什么问题(例如,当我们有一个层次结构的类,或者可能抛出异常的类成员时)?
【问题讨论】:
-
这就是为什么我们有RAII。在您的情况下,如果
m是std::unique_ptr<int>,则不会有泄漏。 -
“是否可以在不使用任何智能指针的情况下解决这个问题?” - 奇怪的问题,因为这个问题是由于缺少使用智能指针引起的
-
不使用智能指针?当然,您可能会捕获异常,删除
m,然后像往常一样重新抛出。
标签: c++