[英]How is memory allocated in constructor released when the constructor throws an exception?
Below is my sample code. 以下是我的示例代码。 Base class has a pointer of A class with memory assigned from heap using new operator.
基类具有A类的指针,其中使用new运算符从堆分配内存。 I am explicitly throwing an exception.
我明确地抛出异常。 Since I am not invoking delete on *ptr the memory allocated by new is not released.
由于我没有在* ptr上调用delete,因此未分配new分配的内存。 Since the object is not constructed completely how can we release memory?
由于对象没有完全构造,我们如何释放内存?
#include <iostream>
using namespace std;
class A
{
public:
A()
{
cout<<"A::ctor"<<endl;
}
~A()
{
cout<<"A::Dctor"<<endl;
}
};
class Base
{
public:
A *ptr;
Base()
{
ptr = new A();
cout<<"Base::Ctor"<<endl;
throw std::exception();
}
~Base()
{
delete ptr;
cout<<"Base::Dtor"<<endl;
}
};
int main()
{
try{
Base bobj;
}
catch(exception e)
{
cout<<e.what();
}
return 0;
}
When Base constructor throws exception the control goes to catch block and exception is handled. 当Base构造函数抛出异常时,控件转到catch块并处理异常。 But how is the memory allocated by
ptr = new A();
但是如何通过
ptr = new A();
分配内存ptr = new A();
released? 释放?
Now I know using smart pointers would solve the issue. 现在我知道使用智能指针可以解决问题。 But before C++11 how were such situations handled.
但在C ++ 11之前,如何处理这种情况。
In addition, I would like to know how do we close file handlers of a file handler is opened in constructor and constructor has an exception? 另外,我想知道我们如何在构造函数中打开文件处理程序的文件处理程序,并且构造函数有异常?
Base()
{
ofstream myfile;
myfile.open("myfile.txt");
..........
throw std::exception();
}
~Base()
{
myfile.close();
}
The memory associated with ptr
is never released! 与
ptr
相关的内存永远不会释放!
Yes, that was always a problem. 是的,这总是一个问题。
Prior to C++11 you could build your own smart pointer class (or use the one in Boost for example), or take care to delete
prior to throwing an exception. 在C ++ 11之前,你可以构建自己的智能指针类(或者使用Boost中的那个),或者在抛出异常之前注意
delete
。 Putting ptr
in a base class is also an alternative: the base class constructor will complete before the derived constructor's function body is reached. 将
ptr
放在基类中也是一种替代方法:基类构造函数将在到达派生构造函数的函数体之前完成。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.