我正在阅读这篇关于it技术的文章,其中提到:
注意:如果构造函数以抛出异常结束,则与对象本身相关联的内存将被清理 - 没有内存泄漏。例如:
void f()
{
X x; // If X::X() throws, the memory for x itself will not leak
Y* p = new Y(); // If Y::Y() throws, the memory for *p itself will not leak
}
我很难理解这个问题,希望有人能够澄清一下。我尝试了以下示例,它表明如果构造函数内发生异常,则析构函数不会被调用。
struct someObject
{
someObject()
{
f = new foo();
throw 12;
}
~someObject()
{
std::cout << "Destructor of someobject called";
}
foo* f;
};
class foo
{
public:
foo()
{
g = new glue();
someObject a;
}
~foo()
{
std::cout << "Destructor of foo";
}
private:
glue* g;
};
int main()
{
try
{
foo a;
}
catch(int a)
{
//Exception caught. foo destructor not called and someobject destrucotr not called.
//Memory leak of glue and foo objects
}
}
我该如何解决这个问题?
很抱歉更新可能带来的不便。