【问题标题】:Does catch exception by reference need to be deleted?通过引用捕获异常是否需要删除?
【发布时间】:2014-05-16 21:58:31
【问题描述】:

我正在创建一个自定义的异常类

class my_error: public std::exception
{

public:

    //! Constructs parse error
    my_error(const char* param_msg, std::string param_reason) throw()
    {
        msg = param_msg;
        reason = param_reason;
    }
    ~my_error() throw() {}

private:
    string msg;
    string reason

};

然后这样扔

throw my_error("something wrong", "coffee is too hot");

并抓住

catch(ems_error& ex) { 
// do somehitng here 
}

问题:我应该在这个 ex 变量上调用 delete 吗?目前我的程序在没有删除的情况下运行良好,但我担心内存泄漏

【问题讨论】:

  • 无需调用delete。你只需要在堆上创建异常(通过调用new
  • 你会删除什么?你没有指针!
  • 哈哈,谢谢大家的确认!
  • Mark Ransom,指针并不表示堆上有东西。您的评论可能会被误解。

标签: c++ g++


【解决方案1】:

异常对象在处理后会自动销毁。 (参见 C++11 §15.1/4)

【讨论】:

    猜你喜欢
    • 2016-01-28
    • 2019-08-22
    • 1970-01-01
    • 1970-01-01
    • 2015-07-13
    • 2012-11-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多