Pointers, References and Values by Michael D. Crawford Continued...

When to Return Results by Reference

Consider returning a result by reference if the value referred is certain to live on after the function returns.

You can consider returning a reference result when the object referred to is not local to the function. The most important of the cases where this occurs is when you want to return a data member of the function's class, but either don't want to incur the overhead of copying the member object or you want to allow the original to be modified by the recipient. In this case, return a reference to the data member. This can be const or non-const depending on the access you wish to grant to the recipient:

#include "Foo.h"
class Example
{
	public:
		Example();

		const Foo& GetFoo() const { return mFoo; }

	private:
		Foo	mFoo;
};

An important consideration is that the object referred to must live as long as the recipient will keep accessing it. If you call GetFoo() on an Example object to get a reference to its mFoo member, then delete the Example object, your reference will be invalid - using it will likely cause a crash.

I find returning reference results most useful in base class accessors that are declared protected, for use by derived classes. In this case we can be sure of the referenced object's lifetime because the base class object is destroyed after the derived parts.

next button previous page contents all programming tips titles

Copyright © 2000, 2001, 2002, 2005 Michael D. Crawford. All Rights Reserved.

One Must Not Trifle With Wizards For It Makes Us Soggy And Hard To Light