当构造函数抛出异常时,如何删除数据成员的内存

how to delete the memory of data member when exception thrown by constructor

本文关键字:删除 数据成员 内存 何删除 抛出异常 构造函数      更新时间:2023-10-16

我写了一些关于处理构造函数中抛出的异常的代码,通过使用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;
};