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?
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.
The default for the language is return-by-value.
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.
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.
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:
SomeCondition
is something exceptional which clients can not deal with that would be appropriateSomeCondition
should always hold, it should be assertedIf you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With