当构造函数抛出异常时,如何删除数据成员的内存
how to delete the memory of data member when exception thrown by constructor
我写了一些关于处理构造函数中抛出的异常的代码,通过使用placement delete调用析构函数来删除_pBuf
的内存,以防止内存泄漏。我想知道这种方法用起来是否安全。感谢您的帮助!
//this is an example of throwing exception in constructor,
//and showing how to call the destructor to delete the memory allocated in constructor to prevent memory leak,
//using "placement delete"
#include <iostream>
#include <exception>
#include <stdexcept>
using namespace std;
class ConWithException
{
public:
ConWithException() : _pBuf(NULL)
{
_pBuf = new int[100];
cout << "before throw exception in constructor" << endl;
throw std::runtime_error("Exception in Constructor!");
}
~ConWithException()
{
cout << "Destructor!" << endl;
if( _pBuf != NULL )
{
cout << "Delete buffer..." << endl;
delete[] _pBuf;
_pBuf = NULL;
}
else
{
cout << "NULL pBuf" << endl;
}
cout << "Destructor end!" << endl;
}
void * operator new(size_t size){
cout << "placement new" << endl;
return ::operator new(size);
}
void operator delete(void* mem){
cout << "placement delete" << endl;
((ConWithException*)mem)->~ConWithException();
::operator delete(mem);
}
private:
int* _pBuf;
};
int main(int argc, char** argv)
{
ConWithException* cwe = NULL;
try
{
cwe = new ConWithException;
}
catch( std::runtime_error& e )
{
cout<<"exception:"<< e.what() << endl;
}
if (cwe == NULL)
{
cout << " already NULL, no need to delete" << endl;
}
return 0;
}
使用RAII,您不必处理它:
class ConWithException
{
public:
ConWithException() : _pBuf(new int[100])
{
cout << "before throw exception in constructor" << endl;
throw std::runtime_error("Exception in Constructor!");
}
private:
std::unique_ptr<int[]> _pBuf;
};
相关文章:
- 用于访问容器<T>数据成员的正确 API
- 静态数据成员的问题-修复链接错误会导致编译器错误
- 数据成员SFINAE的C++17测试:gcc vs clang
- 派生类是否可以在抽象工厂设计模式中具有数据成员
- 如何在c++中定义以struct为数据成员的类中的构造函数
- 静态数据成员模板专用化的实例化点在哪里
- int数据类型的指针指向的是什么,如果是一个类的私有数据成员,我们创建了该类的两个对象?
- 使用指针访问数组中的对象数据成员
- 友元函数无法访问私有数据成员 (c++)
- 我可以在 C++ 中将数据成员/变量从其定义之外添加到结构中吗?
- 为什么将一个结构的引用设置为等于另一个结构只会更改一个数据成员?
- 将私有数据成员添加到野牛生成的类中
- 输入数据成员未按要求工作
- 二维矢量数据成员
- 在类 A 中创建类型为 B 类的向量 - 访问数据 [C++] [成员在两个类中都是私有的]
- 调用在 HXX 文件中声明的静态数据成员
- 添加/删除具有模板参数的数据成员
- C++析构函数删除包含动态数组作为数据成员的对象时的用法
- 当构造函数抛出异常时,如何删除数据成员的内存
- C++ -<Task> 删除堆上分配的任务数组时,将列表 l(或任何 STL 容器)添加为数据成员会导致错误