C++ Using references as return values

C++ References

Using references instead of pointers makes C++ programs easier to read and maintain. C++ functions can return a reference in a manner similar to returning a pointer.

When a function returns a reference, it returns an implicit pointer to the return value. In this way, the function can be placed on the left side of an assignment statement. For example, consider the following simple program:

Example

#include <iostream> using namespace std; double vals[] = {10.1, 12.6, 33.1, 24.1, 50.0}; double& setValues(int i) { double& ref = vals[i]; return ref; // return a reference to the i-th element; ref is a reference variable, ref refers to vals[i] } // main function to call the function defined above int main () { cout << "value before change" << endl; for ( int i = 0; i < 5; i++ ) { cout << "vals[" << i << "] = "; cout << vals[i] << endl; } setValues(1) = 20.23; // change the 2nd element setValues(3) = 70.8; // change the 4th element cout << "value after change" << endl; for ( int i = 0; i < 5; i++ ) { cout << "vals[" << i << "] = "; cout << vals[i] << endl; } return 0; }

When the above code is compiled and executed, it produces the following results:

改变前的值
vals[0] = 10.1
vals[1] = 12.6
vals[2] = 33.1
vals[3] = 24.1
vals[4] = 50
改变后的值
vals[0] = 10.1
vals[1] = 20.23
vals[2] = 33.1
vals[3] = 70.8
vals[4] = 50

When returning a reference, be careful that the referenced object cannot go out of scope. Therefore, returning a reference to a local variable is illegal, but a reference to a static variable can be returned.

int& func() { int q; //! return q; // error occurs at compile time static int x; return x; // safe, x is still valid outside the function scope }

The following is an example that demonstrates returning a reference to a static variable:

Example

#include <iostream>
using namespace std;

// return a reference to a static variable
int& getStaticRef() {
    static int num = 5; // static variable
    return num;
}

int main() {
    int& ref = getStaticRef(); // get a reference to a static variable
    cout << "initial value:" << ref << endl;

    ref = 10; // modify the value of the static variable

    cout << "value after modification:" << ref << endl;
    cout << "value after calling the function again:" << getStaticRef() << endl;

    return 0;
}

The getStaticRef() function returns a reference to the static variable num.

The output result is:

初始值:5
修改后的值:10
再次调用函数后的值:10

C++ References

other extensions