Return type

Normally when a C/C++ function returns by value, the returning object is copied from the function to the target.


int f1()    // returns by value
{
    int i;  // local variable with automatic storage
    //...
    return i;   // return by value
}

It is also possible to define a function with reference return type. The meaning of this is to bind the function expression to the returning object.


int& f2()    // returns by reference
{
    int i;  // local variable with automatic storage
    //...
    return i;   // returns the reference
}

The usage is different. If the returning object will not survive the function call expression, than we must copy it. Otherwise, it is allowed returning with a reference.


int j = f1();   // ok: value of i has copied into j
int& j = f2();   // bad: no copy, j refers to invalid