在可能失败的函数中重新获取对象引用的最佳方法

Best approach for returing an object reference in a function that can fail

本文关键字:获取 对象引用 方法 最佳 失败 函数 新获取      更新时间:2023-10-16

我正在为一个队列编写一段小代码,允许您等待输入可用。现在,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());

您缺少一个显而易见的解决方案:返回指针而不是引用。空指针表示操作未成功。

我并不提倡这种技术胜过其他技术,但这是过去的做法。