maandag 25 juni 2007

Being carefull what a return reference refers to!

The single most important point to remember when returning a reference is avoid returning a reference to a memory location that ceases to exist when the function terminates!
What you want to avoid is code along these lines:

const sysop & clone2(sysop & sysopref)
{
sysop newguy; // first step to big error
newguy = sysopref; // copy info
return newguy; // return reference to copy
}

This has the unfortunate effect of returning a reference to a temporary variable (newguy) that passes from existence as soon as the function terminates.
Similarly you should avoid returning pointers to such temporary variables.

The simplest way to avoid this problem is to return a reference that was passed as an argument to the function. A reference parameter will refer to data used by the calling function, hence the returned reference will refer to that same data.

A second method is to use new to create new storage.

const sysop & clone(sysop & sysopref)
{
sysop * psysop = new sysop;
*psysop = sysopref; // copy info
return *psysop;
}

The first statement creates a nameless sysop structure. The pointer psysop points to the structure, so *psysop is the structure. The code appears to return the structure, but the function declaration indicates that the function really returns a reference to this structure. You could then use the function this way:

sysop & jolly = clone(looper);

This makes jolly a reference to the new structure. There is a problem with this approach: You should use delete to free memory allocated by new when the memory is no longer needed. A call to clone() hides the call to new, making it simpler to forget to use delete later. The auto_ptr template discussed later can help automate the deletion process.

Geen opmerkingen: