Alex Rivera | Logout

Pointer vs. reference return types

Asked 2011-10-18T21:06:12.103
35

i'm trying to come up with a concrete reasoning why to use a pointer over a reference as a return type from a function ,

my reasoning is that if inadvertently a null value is returned to a reference type it could not be checked , and could lead to run-time errors

  int& something(int j)
  {
      int* p = 0 ;  
      return *p;
  }

  void main()
  {
      int& i = something(5);
      i = 7;   // run-time error 
  }

if i had used a pointer i could check it and avoid the error the pointer return value would act as a contract to that a value must be returned.

 void main()
 {
         int* i = something(5);
         if( i != null )
             *i = 7;
 }

any thoughts would be appreciated again ,

what would you use and why reference or pointer

thanks in advance.

Edit
Report

3 Answers

22

References are a different way of thinking. Think of references as "pointers to existing objects". Once you do that, you'll understand why they can't be NULL - the object exists and the reference points to it.

Therefore, if your function returns a reference to something that it creates, it needs to guarantee that it actually does create a valid object. If it does not, or is unable to, then that is grounds to throw an exception.

Contrast that with a pointer. A pointer can be NULL and the caller will have to deal with a NULL return value. Therefore, if your function cannot guarantee that it will return a valid reference and you don't want to throw exceptions, you will need to use pointers.

answered 2011-10-18T21:20:40.897
3

If you inadvertently return a null value, that's a bug. You can just as easily place the check inside something() and throw an exception if it's null.

Having said that, the historical convention is to return heap objects via pointers, even if they are guaranteed to be non-null.

answered 2011-10-18T21:11:15.180
1

If your function is intended to "always" return a value, then your function should return a reference.

In those cases where, for some exceptional reason, you cannot find the value to return, you should throw an exception.

You should not rely on there being a run-time error generated when you try to return a reference to a null or wild pointer. The behavior is undefined. Anything could happen.

answered 2011-10-18T21:19:54.873

Your Answer