在可能失败的函数中重新获取对象引用的最佳方法
Best approach for returing an object reference in a function that can fail
我正在为一个队列编写一段小代码,允许您等待输入可用。现在,std::queue有front函数,它返回对top对象的引用,我想坚持类似的设计。问题是,我想允许该选项等待X毫秒才能获得输入。这意味着我还必须返回一些关于等待的状态(比如说,true表示成功,false表示超时)。我可以用两种方法:
std::pair<bool, T&> frontWait(const std::chrono::milliseconds& timeout);
出于某种原因,我并不喜欢它,它只是与其他函数签名不同,它们要么返回T&,嘘,或者什么都没有。或者我可以有这样的东西:
T& frontWait(const std::chrono::milliseconds& timeout, bool& waitResult);
我也不太喜欢。
也许有一种方法我错过了?(在超时时抛出异常对我来说并不好,因为这根本不是一个异常),如果不是,哪种方法会更好?
您可能需要考虑boost::optional<>
。
boost::optional<T&> frontWait(const std::chrono::milliseconds& timeout);
在呼叫现场:
boost::optional<T&> result = frontWait(500);
if (result) {
// Note the syntax similar to pointers, but boost::optional is not a pointer,
// as you can read from its documentation.
// Assume that doSomething has a prototype something like this:
// void doSomething(const T& x);
// or:
// void doSomething(T& x);
//
doSomething(*result);
}
如果出于某种原因,您不想使用boost::optional
,我认为另一个好的选项可以是简单的bool返回选项,当结果值通过引用参数返回给调用者时
bool frontWait(const std::chrono::milliseconds& timeout, T& result);
检查Boost可选。你不需要使用它。如果需要,你可以实现自己的。
据我回忆,它的工作原理类似于:
optional<T&> frontWait(const std::chrono::milliseconds &timeout)
auto response = frontWait(1000);
if(response) dosomething(response.get());
您缺少一个显而易见的解决方案:返回指针而不是引用。空指针表示操作未成功。
我并不提倡这种技术胜过其他技术,但这是过去的做法。
相关文章:
- 返回常量对象引用 (getter) 和仅返回字符串有什么区别?
- 我可以从列表中获取对象并复制它们,但如何删除我复制的对象?
- 从自定义类获取对象向量中的 max 元素
- 如何从函数中获取对象?
- 给定一个指向对象的超类指针,如何获取对象的大小?
- 我们可以有一个 setter 成员函数作为从 const 对象引用的 const 吗?
- C++对象引用返回不同的值
- 对象引用中的字段以不同的方法返回不同的值
- 如何使用 decltype 获取没有引用的指针?
- 通过向构造函数其他对象引用页面来创建对象
- Cython正在获取C++对象列表的长度
- 只需调用对象即可获取对象数据
- 使用 decltype(this) 获取函数引用
- 是否可以在C 中获取对象的随附文件的名称
- 为什么在对象引用恒定时允许更改为另一个类的指针的成员变量
- 如何在C++中读取 HDF5 对象引用
- 如何获取对象的const引用并使用该引用更改对象(使用const_cast)
- 设置和获取对象之间的变量而不引用它们
- 在可能失败的函数中重新获取对象引用的最佳方法
- 如何获取对象的当前引用计数