【问题标题】:Will handling errors through out parameter cause a memory leak?通过 out 参数处理错误会导致内存泄漏吗?
【发布时间】:2013-02-15 07:15:57
【问题描述】:

我目前正在学习/使用 c++,但我来自 Java 背景,所以如果这是一个愚蠢的问题,我深表歉意。下面是一些代码,代表我处理由外部 API 生成的错误的方式。但是,我不确定当我为我的错误处理输出参数赋值时是否会导致内存泄漏。

class ExceptionHandler {

private:
    std::string _msg;
    int _code;

public:
    ExceptionHandler(std::string msg = "", int code = 0) : 
         _msg(msg),
         _code(code)
    {
    }

    int code() {
        return _code;
    }
    std::string msg() {
        return _msg;
    }

}

 //This method returns true if it was executed with no errors
 //It returns false if an error occurred

    bool foo(ExceptionHandler * errHandler = NULL) {

        int sts; 

        //The API functions return 0 if completed successfully
        //else they returns some error code

        sts = some_api_func1();

        if(sts != 0) { //An error occurred!
            if(errHandler) {
                ExceptionHandler handler("Error from func1",sts);
                *errHandler = handler; //<--- Will this cause a memory leak since I would be losing errHandler's original value??
            }
            return false;
        }

        //My motivation for using exception handling this way is that I can 
        //set the handler's message based on what part it failed at and the 
        //code associated with it, like below:

        sts = some_api_func2();

        if(sts != 0) { //An error occurred!
            if(errHandler) {
                ExceptionHandler handler("Error from func2",sts); //<--- Different err message
                *errHandler = handler; //<--- But does this cause a memory leak?
            }
            return false;
        }

        return true;
    }


//Main method

int main() {
    ExceptionHandler handler;

    if(!foo(&handler)) {

        std::cout << "An exception occurred: (" << handler.code() << ") " << handler.msg() << std::endl;

    } else {

        std::cout << "Success!" << std::endl;

    }


}
  • 如果发生错误,方法“foo()”会导致内存泄漏吗?

  • 如果是这样,我该如何解决?如果没有,怎么没有?

  • 这是处理错误的好方法吗?

提前谢谢你!

编辑

我了解到上面的代码不会产生内存泄漏,但下面的代码是处理错误的更好方法(谢谢大家!):

void foo() {

    int sts;

    sts = some_api_func1();


    if(sts != 0) 
        throw ExceptionHandler("Error at func1",sts);

    sts = some_api_func2();

    if(sts != 0)
        throw ExceptionHandler("Error at func2",sts);
}

int main() {

    try {
        foo();
        std::cout << "Success!";
    } catch(ExceptionHandler &e) { //<--- Catch by reference
        std::cout << "Exception: (" << e.code() << ") " << e.msg();
    }


}

【问题讨论】:

  • 更糟糕的是,处理程序是在堆栈上声明的。一旦你的函数返回,那个内存就不再有效,“坏”的事情就会发生。不是内存泄漏,而是等待发生的段错误。
  • 你知道C++已经有异常机制了吧?你可以抛出一个错误。
  • “这种方式是我可以根据失败的部分和与之关联的代码来设置处理程序的消息” - 有更方便的方法来实现相同的。一个简单的throwing 异常在这里就足够了......有一些方法甚至可以从中获取堆栈跟踪,以便您可以准确地看到异常“经过”的整个路径......
  • 这个问题的简短回答是你没有使用关键字new,所以你不可能有内存泄漏。
  • @SoulDZIN 除非您使用嵌入式系统等严格的约束。在这种情况下,抛出异常是正确的做法。

标签: c++ memory-leaks error-handling


【解决方案1】:
ExceptionHandler handler;
if (!foo(&handler)) {
    //...
}

定义一个具有自动存储期限的对象,其地址被传递给foo函数。顺便说一句,如果你知道你总是将参数传递给函数,那么通过引用而不是指针传递它。

bool foo(ExceptionHandler * errHandler = NULL) {
    ExceptionHandler handler("Error in foo", 1);
    *errHandler = handler;
}

还创建了另一个具有自动存储持续时间的ExceptionHandler 实例,因此一旦执行超出范围,该对象就会被销毁。不过没关系,因为*errHandler = handler;使用了默认的赋值操作符,将handler的数据成员的值复制到errHandler指向的对象中,所以这里没有没有内存泄漏案例。

“这是处理错误的好方法吗?”

没有。这不是处理错误的正确方法。请改用异常。只要确保您最终不会滥用异常作为通过程序传递数据的另一种方式。所以我建议你也看看:Why should exceptions be used conservatively?

其他相关问题:
Is there a general consensus in the C++ community on when exceptions should be used?
"We do not use C++ exceptions" — What's the alternative? Let it crash?


一旦决定使用异常,请确保按值抛出并按引用捕获:

if (...)
    throw MyException(...);

在某处:

try {
    ...
} catch (MyException& e) {
    ...
}

【讨论】:

  • 好的,是不是因为这个异常引用了抛出的异常,所以它不会被复制?
  • @SoulDZIN:是的,但背后的主要原因是避免切片。如果您抛出 MySpecialException1 类型的异常,但您会按值捕获其基类:catch (MyException e),则特定于 MySpecialException1 类的自定义数据成员将丢失。
  • 有趣,我会记下这一点并更改我的编辑,谢谢!
猜你喜欢
  • 2011-11-14
  • 1970-01-01
  • 1970-01-01
  • 2012-11-04
  • 2021-03-23
  • 2021-09-25
  • 2014-12-08
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多