Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best way to return early from a function returning a reference

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?

like image 286
Konrad Avatar asked Nov 18 '09 10:11

Konrad


People also ask

How do you return a reference from a function?

A C++ function can return a reference in a similar way as it returns a pointer. When returning a reference, be careful that the object being referred to does not go out of scope. So it is not legal to return a reference to local var. But you can always return a reference on a static variable.

Does C return value or reference?

The default for the language is return-by-value.

What does it mean to return by reference?

If you return it by reference, you are returning an alias to that same variable. If you pass it to another method by reference, you are passing a reference to the variable it aliases. When you make a ref local alias, you make a new alias to the same variable.

Is it unsafe to return a local variable by reference?

It is dangerous to have a dangling pointer like that as pointers or references to local variables are not allowed to escape the function where local variables live; hence, the compiler throws an error.


1 Answers

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
like image 168
sbi Avatar answered Sep 28 '22 04:09

sbi