转载
http://baimafujinji.blog.51cto.com/907111/195792
引用作为函数的返回值时,函数的返回值可以理解为函数返回了一个变量(事实上,函数返回引用时,它返回的是一个指向返回值的隐式指针),因此,值为引用的函数可以用作赋值运算符的左操作数。另外,用引用返回一个函数值的最大好处是,在内存中不产生被返回值的副本。
#include<iostream>
using namespace std;
int &func()
{
static int num = 0;
return ++num;
}
int main()
{
int i;
for(i=0; i<5; i++)
cout<<func()<<'\t';
cout<<endl;
func()=10;
for(i=0; i<5; i++)
cout<<func()<<'\t';
cout<<endl;
}
/*
$ g++ -o test test1.cpp
$ ./test
1 2 3 4 5
11 12 13 14 15
*/
不能返回函数内部动态分配的内存的引用。虽然不存在局部变量的被动销毁的问题,但是在此种情况下,仍然存在一些问题。例如,被函数返回的引用只是作为一个临时变量出现,而没有被赋予一个实际的变量,那么这个引用所指向的由new分配的空间就无法被释放,从而造成内存泄漏问题。
举例如下:
$ g++ -o test2 test2.cpp
test2.cpp: In function ‘int*& fun()’:
test2.cpp:8:7: warning: reference to local variable ‘p’ returned [-Wreturn-local-addr]
int *p = new int(1);
^
举例如下:
#include <iostream>
int *& fun()
{
int *p = new int(1);
return p;
}
int main()
{
int *a;
a = fun();
}
$ g++ -o test2 test2.cpp
test2.cpp: In function ‘int*& fun()’:
test2.cpp:8:7: warning: reference to local variable ‘p’ returned [-Wreturn-local-addr]
int *p = new int(1);
^