如何返回“未找到"当返回值是 const 引用时 [英] How to return "not found" when return value is const reference

查看:60
本文介绍了如何返回“未找到"当返回值是 const 引用时的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个问题,当我使用这样的东西时:

I have a problem that when I use something like this:

const MyList& my_list = getListForThisRegion(/*region ID, ...*/);

当找不到值时,我不知道返回什么.

I dont know what to return when no value is found.

我的问题是我想有一种方法来向调用者发送信号(当从 getListForThisRegion 返回值时)未找到值".如果我返回一个指针,我可以返回 nullptr,但我不知道如何使用引用来做到这一点.我能想到的就是有一些 MyList 类型的静态成员 not_found,并返回对它的引用,但它看起来很丑.

My problem is that I would like to have a way to signal (when returning value from getListForThisRegion) "value not found" to the caller. If I was returning a pointer, I could return nullptr, but I don't know how to do it with references. All I can think of is having some static member not_found of type MyList, and returning a reference to it, but it seems ugly.

是的,我无法返回值,因为列表很胖"并且经常使用.

And yes, I can't return value because lists are "fat" and often used.

很多很好的答案,但异常不是一个可接受的解决方案,因为它被引发的次数很高(nbNotFound/nbCalls 的百分比很高).
关于 boost::optional - 掌握有多复杂?我的意思是它是否需要一些不明显的知识(不明显=不仅仅是知道语法的东西)?

ton of great answers , but exception is not an acceptable solution because the number of times it would be raised is high (the percentage nbNotFound/nbCalls is high).
regarding boost::optional - how complicated it is to master? I mean does it require some non obvious knowledge (non obvious= something that is not simply knowing the syntax)?

推荐答案

有两种惯用的方法来处理这个问题:

There are two idiomatic ways to handle this:

  • 更改您的接口以返回一种可以不引用任何内容的类型(例如,可以为 null 的指针、指向 end 的迭代器).
  • Change your interface to return a type that has the ability to refer to nothing (e.g. a pointer that can be null, an iterator to end).

或者

  • 如果未找到该项目,则抛出异常.

返回一个虚拟对象有点麻烦,返回一个指针并没有任何好处,因为您仍然需要根据特殊值(null 或虚拟对象)检查结果.

Returning a dummy object is a bit hacky, and you don't gain anything over returning a pointer as you still have to check the result against a special value (null or the dummy object).

这篇关于如何返回“未找到"当返回值是 const 引用时的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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