nsvir
nsvir

Reputation: 8971

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?

Upvotes: 4

Views: 2604

Answers (4)

Vlad from Moscow
Vlad from Moscow

Reputation: 311186

The right way is to throw an exception of type std::out_of_range in case parameter position has no acceptable value.

Upvotes: 3

Jmc
Jmc

Reputation: 830

One other thing to think about is that, even if you were returning an 'int' (i.e. not a reference), NULL would be 0 (and so easily confused with a valid int value that is '0').

If you want to stick to this function definition, then throw an exception to signal an error.

int&     MyClass::getElement(int position)
{
   if (position < _size)
      return (_array[position]);

   throw std::out_of_range("Invalid size to getElement");
}

Upvotes: 0

Mike Seymour
Mike Seymour

Reputation: 254771

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.

Upvotes: 6

Wojtek Surowka
Wojtek Surowka

Reputation: 21013

If you need to return reference, you have to throw an exception in case of error.

Upvotes: 0

Related Questions