简体   繁体   English

从 C++ 函数返回有意义的错误 - 最佳实践

[英]Returning Meaningful Errors From C++ Function - Best Practice

I'm writing a class that has functions that can return multiple different types of errors depending on what point the function(s) stop working.我正在编写一个类,该类的函数可以根据函数停止工作的时间点返回多种不同类型的错误。 As it stands now I don't have a formal idea of how to do this, but I've seen something similar to:就目前而言,我对如何做到这一点没有正式的想法,但我看到了类似的东西:

bool thisFunctionReturnsError(type param1, type param2, returntype& return)

This works, it returns true/false if an error occurs and otherwise will return a valid "returntype" into the return variable for the programmer to use.这是有效的,如果发生错误,它返回真/假,否则将返回一个有效的“返回类型”到返回变量中供程序员使用。 But my question is - is this the best practice?但我的问题是 - 这是最佳实践吗?

I found the below topic but it's in regards to C. I'm curious if C++ has a better way to do this that doesn't involve exceptions (because they're not standard).我找到了下面的主题,但它是关于 C 的。我很好奇 C++ 是否有更好的方法来做到这一点,不涉及异常(因为它们不是标准的)。

What is the best way to return an error from a function when I'm already returning a value? 当我已经返回一个值时,从函数返回错误的最佳方法是什么?

Can anyone give me some advice on this?任何人都可以给我一些建议吗? Thank you!谢谢!

Technically if the error is something that shouldn't happen in normal operation, this is what C++ expects you to use exceptions for, and they are as standard as anything else in C++.从技术上讲,如果错误是正常操作中不应该发生的事情,那么这就是 C++ 期望您使用异常的原因,并且它们与 C++ 中的任何其他内容一样标准。

However, if the error may be a part of normal program flow, or if due to performance exceptions are not an option, consider returning a std::pair , or std::optional (C++14 or boost) if just the fail/succeed information is needed.但是,如果错误可能是正常程序流程的一部分,或者由于性能异常不是一个选项,请考虑返回std::pairstd::optional (C++14 或 boost),如果只是失败/succeed 信息是必需的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM