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

How to Return Results from Functions

Return a result by value if it is certain to exist. Otherwise return a pointer.

Prefer Returning Results by Value or Pointer

When a function returns a result to a caller, the result must continue to exist after the function has exited. All of the objects that were stored by value on the stack in the function will have been destroyed before the caller recieves the results.

For this reason, you usually want to return a result by value. You can return a pointer to an object that you have allocated, with the understanding that the caller takes ownership of the pointer, but you cannot return pointers to objects held on the stack - the pointers will be invalid as soon as they are received. Similarly, you cannot return references to local objects.

A convenience and potential for optimization is to declare that you return an object of some class but at the return statement, pass back some other type that the actual result will be constructed from:

string MyClass::GetName()
{
	// returns a C string, from which an
	// STL string will be constructed
	return "Mike";
}

In the code above, the return statement implicitly calls string::string( const char * ) to construct a C++ string from a C string. (But note that this particular example is inefficient because we are always converting a constant string. It would be faster to initialize a static constant STL string from the C string constant and return that because the conversion would occur only once.)

The following two functions are incorrect and will likely lead to either crashes or corrupt data:

string *ReturnsBadPointer()
{
	string disappearing( "Bogus" );

	return &disappearing;	// pointer will be invalid after return
}

string &ReturnsBadReference()
{
	string disappearing( "Bogus" );

	return disappearing;
}
next page 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