Pointers, References and Values by Michael D. Crawford Continued...
Return a result by value if it is certain to exist. Otherwise return a 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 can be constructed from:
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:
Voting for GoingWare at The Programming Pages will encourage more
people to read these articles.
Copyright © 2000, 2001, 2002, 2005 Michael D. Crawford. All Rights Reserved.