我目前正在学习/使用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();
}
}
答案 0 :(得分: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) {
...
}