Is there a "return NULL" equivalent for return-by-reference functions?

198 views Asked by At

I'm working with existing code that returns a reference, something like this:

int &func()
{
   static int i = 5;
   return i;
}

I would like to return an error case as "NULL" but of course NULL doesn't work in a return-by-reference function. If this were returning a pointer I might do this:

int *func()
{
   static int i = 5;

   if (!good)
       return NULL;
   else
       return &i;
}

Besides converting to a pointer-based return value, is there a best practice for returning a failure state?

3

There are 3 answers

0
Ahmed AEK On BEST ANSWER

yes, c++17 introduced std::optional, which can be empty, but it cannot have a reference so std::optional<<std::reference_wrapper<int>> is the proper "standard" return.

std::optional<<std::reference_wrapper<int>> func()
{

   static int i = 5;

   if (!good)
       return std::nullopt;  // return {}; works here
   else
       return i;
}

later c++20 introduced std::expected which can also return an Error Type to signal more information than just a "failure".

even if you are using older c++ standards you can still use optional in c++11 libraries, same as expected in c++11 libraries.


c++11 optional library can hold a reference, so you can use it for cleaner code.

tl::optional<int&> func()
{

   static int i = 5;

   if (!good)
       return tl::nullopt;  // return {}; works here
   else
       return i;
}
0
Christian Halaszovich On

std::optional seems to be what you're looking for. See https://en.cppreference.com/w/cpp/utility/optional

1
JohnFilleau On

std::optional<T> cannot take a reference type, so std::optional<int&> is invalid. I'd recommend returning a pointer here, and setting it to nullptr in the error case. It is Good and Valid C++ to return a non-owning pointer.

int* func()
{

   static int i = 5;

   if (!good)
       return nullptr;
   else
       return &i;
}