局部变量与函数返回地址

来源:互联网 发布:慧算账软件好用吗 编辑:程序博客网 时间:2024/05/22 20:28


弄清楚了局部变量的存储方式与生命期之后,当用指针或引用从函数中返回一个

地址时不要返回局部变量的指针或引用



实例一:

#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

原创粉丝点击