什么是在C ++中返回错误代码的正确方法 [英] Whats the right approach to return error codes in C++

查看:167
本文介绍了什么是在C ++中返回错误代码的正确方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用错误代码来处理c ++项目中的错误。问题是如何从应该返回某些变量/对象的函数中返回错误代码。

I'm using error codes for handling errors in my c++ project. The problem is how to return error codes from a function which is supposed to return some variable/object.

请考虑以下问题:

long val = myobject.doSomething();

在这里,myobject是某个类的对象。如果doSomething函数遇到一些错误情况,那么它将如何通知调用者(不使用异常)。

Here, myobject is an object of some class. If doSomething function encounters some error condition then how should it notify the caller (Without using exceptions).

可能的解决方案:


  1. 在类中有一个数据成员(例如err_),调用者可以检查该成员。但是,在共享相同对象并调用相同函数的多线程应用程序中,这是不安全的。

  2. 使用一些全局错误变量,在多线程环境中再次出现相同的问题。
  3. li>
  1. Have a data member (say err_) in the class which can be checked by the caller. But it would be unsafe in a multi-threaded application sharing the same object and calling the same function.
  2. Use some global error variable, again same issue in a multi-threaded environment.

现在如何通知某些错误情况?

Now how can I notify the caller about some error condition?

推荐答案

您可以传递变量作为参考,并在其中返回错误代码。

You can pass variable as reference and return error code in it.

这篇关于什么是在C ++中返回错误代码的正确方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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