从返回引用的函数早期返回的最佳方式 [英] Best way to return early from a function returning a reference

查看:143
本文介绍了从返回引用的函数早期返回的最佳方式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

让我们假设我们有一个形式的函数:

  const SomeObject& SomeScope :: ReturnEnterObject()
{
if(!SomeCondition)
{
// return early
return;
}

return ourObject;
}

很明显,上面的代码有一个问题,如果条件失败,问题是如何从这个函数返回。
我的问题的关键是处理这种情况的最好方法是什么?

解决方案

一个句法问题,但是一个设计问题。你必须指定 ReturnOurObject()应该在 SomeCondition 为真时返回。这主要取决于将要使用的功能。你还没有告诉我们。



根据设计问题,我看到了一些可能的语法方法:




  • 返回对其他对象的引用;你必须在某处有一些ersatz对象

  • 在返回引用的地方有一个特殊的无对象到返回对象;客户可以检查这一点;如果他们不检查他们得到合理的默认行为

  • 返回一个指针,而不是一个引用;客户端必须始终检查函数的返回值

  • 抛出异常;如果 SomeCondition 是客户无法处理的异常,那么这是适当的

  • assert;如果 SomeCondition 应始终保持,则应断言


Let us say we have a function of the form:

const SomeObject& SomeScope::ReturnOurObject()
{
    if( ! SomeCondition )
    {
        // return early
        return  ;
    }

    return ourObject;
}

Clearly the code above has an issue, if the condition fails then we have a problem as to how to return from this function. The crux of my question is what is the best way to handle such a situation?

解决方案

This isn't a syntactic issue, but a design issue. You have to specify what ReturnOurObject() is supposed to return when SomeCondition is true. That depends mainly on what the function is going to be used for. And that you haven't told us.

Depending on the design issues, I see a few possible syntactic ways out of this:

  • return a reference to some other object; you would have to have some ersatz object somewhere
  • have a special "no-object-to-return" object somewhere that you return a reference to; clients can check for this; if they don't check they get reasonable default behavior
  • return a pointer, not a reference; clients would have to always check the return value of the function
  • throw an exception; if SomeCondition is something exceptional which clients can not deal with that would be appropriate
  • assert; if SomeCondition should always hold, it should be asserted

这篇关于从返回引用的函数早期返回的最佳方式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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