Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Return error when returning a reference

A function returns a reference on int

int&     MyClass::getElement(int position)
{
   if (position < _size)
      return (_array[position]);
   return ([...]) // An Error
}

My first think was to return NULL. But obviously a reference can not be NULL.

What is the right way to return an error in this case?

like image 219
nsvir Avatar asked Feb 15 '23 00:02

nsvir


1 Answers

Various options, roughly ordered with my preferred options first:

  • Throw an exception, conventionally std::out_of_range
  • Return a pointer
  • Return some other type with a well-define invalid value, like std::pair<bool,int&> or boost::optional<int&>. This is more useful if you want to return something by value, not reference, so can't return a pointer.
  • Return a reference to a static magic number, if you can choose a number which will never be valid data. This is nasty since there's nothing to stop the caller from modifying it.
like image 102
Mike Seymour Avatar answered Feb 24 '23 17:02

Mike Seymour