C++ Returning a Reference
Using references instead of pointers makes C++ programs easier to read and maintain. A C++ function can return a reference in a way similar to returning a pointer.
When a function returns a reference, it returns an implicit pointer to the return value. Thus, the function can be placed on the left side of an assignment statement. For example, please see the simple program below:
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 that refers to vals[i]
}
// Main function to call the function defined above
int
main
(
)
{
cout
<<
"
Values 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
<<
"
Values after change
"
<<
endl
;
for
(
int
i
=
0
;
i
<
5
;
i
++
)
{
cout
<<
"
vals[
"
<<
i
<<
"
] =
"
;
cout
<<
vals
[
i
]
<<
endl
;
}
return
0
;
}
When the code above is compiled and executed, it produces the following result:
改变前的值
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, note that the referenced object must not go out of scope. Therefore, returning a reference to a local variable is illegal, but you can return a reference to a static variable.
int
&
func
(
)
{
int
q
;
//! return q; // error occurs at compile time
static
int
x
;
return
x
;
// safe; x remains valid outside the function scope
}
The following is an example demonstrating returning a reference to a static variable:
Example
#include
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
(
)
;
// obtain a reference to the static variable
cout
<<
"Initial value:"
<<
ref
<<
endl
;
ref
=
10
;
// modify the value of the static variable
cout
<<
"Modified value:"
<<
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 is:
初始值:5
修改后的值:10
再次调用函数后的值:10
C++ References