10.3 引用做函数的返回值
引用做函数的返回值时,不要返回局部变量的引用,这跟不要返回局部变量的指针时一个道理。因为局部变量在函数执行完毕之后就释放掉了,这样返回的引用也引用了一个寂寞,没意义。但跟之前一样,编译器仍会做一次保留。
#include<iostream>
#include<string>
using namespace std;
//不要返回局部变量的引用
int& test1()
{
int a = 10;
return a;
}
int& test2()
{
static int a = 10;
return a;
}
int main()
{
int& ref1 = test1();
cout << "ref1=" << ref1 << endl; //第一次正确,编译器做了保留
cout << "ref1=" << ref1 << endl; //错误
int& ref = test2();
cout << "ref=" << ref << endl;
cout << "ref=" << ref << endl;
test2() = 1000;
cout << "ref=" << ref << endl;
cout << "ref=" << ref << endl;
system("pause");
return 0;
}
我这个编译器第一次也没做保留。