Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

In C++, is there a "return NULL" equivalent for return-by-reference functions?

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

yes, c++17 introduced std::optional, which can be empty, so an std::optional<int&> is a valid return.

std::optional<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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading