在C++中抛出异常后应该如何释放内存?

Dan*_*Dan 6 memory malloc exception c++03

如果这个问题是重复的,我很抱歉 - 我搜索了一段时间,但是我的Google-fu可能不符合要求.

我正在修改一个调用C库的C++程序.C库分配一堆内存(使用malloc()),C++程序使用它然后释放它.问题是C++程序可以在执行过程中抛出异常,从而导致分配的内存永远不会被释放.

作为一个(相当做作的)例子:

/* old_library.c */
char *allocate_lots() {
    char *mem = (char *)malloc(1024);
    return mem;
}

/* my_prog.cpp */
void my_class::my_func () {
    char *mem = allocate_lots();
    bool problem = use(mem);
    if (problem)
        throw my_exception("Oh noes! This will be caught higher up");
    free(mem);  // Never gets called if problem is true
}
Run Code Online (Sandbox Code Playgroud)

我的问题是:我应该怎么处理这个问题?我的第一个想法是将整个事物包装在一个try/catch块中,并且在catch中只需检查并释放内存并重新抛出异常,但这对我来说似乎没有优点和笨重(如果我不顺利的话)想要真正捕获异常).有没有更好的方法呢?

编辑:我可能应该提到我们正在使用g ++ 4.2.2,从2007年开始使用std :: unique_ptr之前.将它归结为企业惯性.

Chr*_*odd 8

std::unique_ptr与自由调用的自定义删除器一起使用:

class free_mem {
public:
    void operator()(char *mem) { free(mem); }
};

void my_class::my_func() {
    std::unique_ptr<char, free_mem> mem = allocate_lots();
Run Code Online (Sandbox Code Playgroud)

  • 编写您自己的unique_ptr替换,然后向您的老板解释为什么您花了2天时间调试一个基本语言工具,如果他们允许升级,您将免费获得.重复它,直到它们开始加权过时工具浪费的时间与升级所花费的时间. (7认同)

Cas*_*sey 5

把那个流氓包起来:

struct malloc_deleter {
  template <typename T>
  void operator () (T* p) const {
    free(p);
  }
};

void my_class::my_func () {
    std::unique_ptr<char[],malloc_deleter> mem{allocate_lots()};
    bool problem = use(mem.get());
    if (problem)
        throw my_exception("Oh noes! This will be caught higher up");
}
Run Code Online (Sandbox Code Playgroud)