Return Values
| Rule 25. Always specify the return type of a function explicitly. |
If you do not specify a return type (and that may be void) C and C++ implicitly declare these functions with int as their return type. Because this is not intuitive and error-prone, always specify the return type. If a function does not return a value, specify its return type as void.
| Rule 26. A function must never return a reference or a pointer to a local variable. |
This is a common beginners mistake, especially with references. It does not make any sense to return a pointer or reference to a local variable, simply because when the program execution is transferred to the caller, the local variables do not exist any more. The only exception are static local variables, but this will also cause problems in multithreaded applications when to different threads get pointers to the same variable.
| Rule 27. Avoid objects as return types, prefer pre-defined data types or pointers instead. |
To enlighten the problem with returning objects, consider the following piece of code:
// Declarations
class Sound { ... };
Sound recordSound(); // Records sound and returns object
...
// Later in the program
Sound snd;
snd = recordSound();
|
Although absolutely legal and readable, this piece of code may incur a big performance hit. What exactly is going on? Let us have a look at the lifetime of all objects:
- An object snd of type Sound is created on the stack.
- The call to recordSound creates another temporary Sound object on the stack.
- As soon as recordSound returns, the assignment operator of class Sound is called in order to copy the contents of the temporary object returned before into the object snd.
- The temporary object on the stack is destroyed.
// Declarations
class Sound { ... };
Sound* recordSound(); // Records sound and returns object
...
// Later in the program
Sound* snd = NULL;
snd = recordSound();
|
In this case the function recordSound allocates a Sound-object using new and simply returns the pointer. This can be done very efficiently by the compiler using a single register. Of course then the main program has to take care of the newly created object and it has to free it by calling delete or by another mechanism.
| Exception to 27. If a class has standard constructor, destructor and assignment operator, a function declared as inline may return an object of that class. |
This is the only exception when you might consider to return objects, as the compiler has a good chance to eliminate most of the object construction, assignment and destruction by aggressive optimisation. To enable such an optimisation it is important that the class only has members of built-in types, has the default destructor and assignment operator.
Kaya Memisoglu 2005-01-06
