C ++。如何返回空指针而不是函数返回类型? [英] C++. How to return null pointer instead of function return type?

查看:337
本文介绍了C ++。如何返回空指针而不是函数返回类型?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个检查正则表达式并根据正则表达式结果返回 std :: vector< int> 的函数。我需要检查功能是否失败/成功。成功返回矢量对象后,失败时 nullptr 以后再检查 if(somefunc()== nullptr)//做些东西

I have a function that checks regex and returning std::vector<int> according to regex result. I need to check if function fail/success. On success return vector object, on fail nullptr to later check if (somefunc() == nullptr) // do smth

推荐答案

返回类型 std :: vector< int> 的值不能为 nullptr

在这种情况下,最直接的方法是返回 std: :unique_ptr< std :: vector< int>> 代替-在这种情况下,可以返回 nullptr

The most straightforward way in this case is to return std::unique_ptr<std::vector<int>> instead - in this case it's possible to return nullptr.

其他选项:


  • 在失败的情况下引发异常

  • 使用 optional< std :: vector< int>> 作为返回类型( boost :: optional std :: optional (如果您的编译器具有C ++ 17功能)

  • 返回 bool 参数,并且将 std :: vector< int>& 作为函数的输出参数

  • throw an exception in case of fail
  • use optional<std::vector<int>> as return type (either boost::optional or std::optional if your compiler has this C++17 feature)
  • return bool parameter and have std::vector<int>& as output parameter of function

最好的方法实际上取决于用例。
例如,如果大小为0的结果向量等于'fail'-可以在代码中随意使用这种知识,只需检查返回向量是否为空即可知道函数是失败还是成功。

The best way to go really depends on the use case. For example, if result vector of size 0 is equivalent to 'fail' - feel free to use this kind of knowledge in your code and just check if return vector is empty to know whether function failed or succeed.

在我的实践中,我几乎总是坚持返回可选 (增强或标准,取决于环境)限制)。
这种接口是陈述结果可以存在或不存在这一事实的最清晰方法。

In my practice I almost always stick to return optional (boost or std, depending on environment restriction). Such interface is the most clear way to state the fact that 'result can either be present or not'.

总而言之,这不是问题只有一个正确的解决方案。
上面列出了可能的选项-而这仅取决于您的个人经验和环境限制/竞争-选择哪个选项。

To sum up - this is not a problem with the only one right solution. Possible options are listed above - and it's only a matter of your personal experience and environmental restrictions/convetions - which option to choose.

这篇关于C ++。如何返回空指针而不是函数返回类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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