Pointer vs. reference return types

You could use a pointer instead of a reference if:

  • Null is a valid return value
  • You dynamically constructed something in the function, and the recipient becomes the owner. (In this case, you might consider returning a smart pointer such as std::unique_ptr or boost::shared_ptr.)

Regardless, you would not want to return either a pointer or a reference to a local variable.


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.


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.


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.