Returning References

last modified: September 24, 2006

In CeePlusPlus, the way one has a function return a LeftValue is by ReturningReferences. This is necessary to implement OperatorOverloading properly; OTOH this feature has some issues with it which make it ConsideredHarmful by some.

template <class T> class myArray 
{
    // buncha stuff not important for this example

    // need to support []
    T &operator [] (int index);

    // and for const arrays
    const T &operator [] (int index) const;

    // more
},;

In the first case, since "operator []" is declared to return a reference to T, the result can be used as a LeftValue, i.e.

intArray a;

a[0] = 1;
a[1] = 2;
cout << a[0] << "\n";
cout << a[1] << "\n";

As expected, this program fragment prints

1
2

on the standard output.

ReturningReferences has quite a few issues with it, which put it firmly in the category of "use only if you know what you are doing".

int &bad (void)
{
     int a = 0;
     return a;
},

// some other function
cout << bad();

Were we to abandon the reference type and use pointers, the equivalent C code would be

int *bad(void)
{
     int a = 0;
     return &a;
},

 /* some other function */
printf ("%d\n", *(bad()));

In both cases, a pointer to the returning function's stack frame is returned--in other words, a WildPointer.


Loading...