弄清楚了局部变量的存储方式与生命期之后,当用指针或引用从函数中返回一个
地址时不要返回局部变量的指针或引用
实例一:
#include<iostream>
using namespace std;
int temp;
int &f1(int x){
temp=x;
return temp;
}
void main(){
int &i=f1(3);
cout<<i<<endl;
cout<<i<<endl;
}
运行结果:
3
3
#include<iostream>
using namespace std;
int &f1(int x){
int temp=x;
return temp;
}
void main(){
int &i=f1(3);
cout<<i<<endl;
cout<<i<<endl; // 因为是局部变量,用过之后就被回收了
}
运行结果:
3
420005