C ++错误处理-使用std :: pair或std :: tuple返回错误代码和函数返回的缺点 [英] C++ Error Handling - downside of using std::pair or std::tuple for returning error codes and function returns

查看:132
本文介绍了C ++错误处理-使用std :: pair或std :: tuple返回错误代码和函数返回的缺点的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在不讨论一般异常与错误代码的讨论的情况下,您认为使用 std :: pair std:tuple的缺点是什么用于返回多个值,即函数的返回值和错误/成功代码,类似于多少去开发人员显然可以进行错误处理

Without getting into the general exceptions vs error codes discussion, what do you think are the downsides of using std::pair or std:tuple for returning multiple values, namely the function's return value AND the error/success code, similar to how many Go developers apparently do error handling?

这种方法显然具有不必使用参数的优点函数返回值或错误代码(取决于您偏爱的方式)。

This approach obviously has the advantage of not having to use out parameters for the function return value or error code (depending on which way around you prefer it).

推荐答案


您认为使用std :: pair或std:tuple返回多个值的缺点是什么,即函数的返回值和错误/成功代码

“what do you think are the downsides of using std::pair or std:tuple for returning multiple values, namely the function's return value AND the error/success code”

这种简单的(C级)故障处理方法的主要缺点是a

The main downside of that simplistic (C level) approach to failure handling is a


  • 安全。

即还有更多可能出错的信息,例如访问不确定的结果值。或者只是在函数没有产生有意义的结果时使用返回值。

I.e. there's more that can go wrong, such as accessing an indeterminate result value. Or just using a return value when the function didn't produce a meaningful one.

旧的Barton& Nackman Fallow 类通过限制对结果值的访问来解决此安全问题。本质上,调用代码必须在使用结果之前检查结果是否存在,并且使用逻辑上不存在的结果值会导致异常或终止。 boost :: optional 类的功能大致相同。

The old Barton & Nackman Fallow class solved this safety problem by restricting access to the result value. Essentially the calling code has to check if there is a result value, before using it, and using a logically non-existent result value causes an exception or termination. The boost::optional class does much the same.

如果您不这样做,如果不希望依赖Boost,那么对于POD结果类型来说,实现 Optional 类是微不足道的,并且可能会导致效率低下(动态分配)一个 std :: vector 来传递非POD可能的结果。

If you don't want a dependency on Boost, then an Optional class is trivial to implement for POD result type, and at a cost of a little possible inefficiency (dynamic allocation) you can just use a std::vector to carry a non-POD possible result.

挑战在于保持清晰度调用代码,这是练习的重点。

The challenge is to retain the clarity of the calling code, which is the whole point of the exercise…

这篇关于C ++错误处理-使用std :: pair或std :: tuple返回错误代码和函数返回的缺点的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆