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

c++ memory-leaks constructor destructor placement-new

144 观看

1回复

55 作者的声誉

我编写了一些有关处理构造函数中引发的异常的代码,方法是使用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;
}
作者: Badboy Lin 的来源 发布者: 2016 年 1 月 8 日

回应 (1)


0

11213 作者的声誉

决定

使用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;
};
作者: Simple 发布者: 08.01.2016 11:46
32x32