我是初学者,在学习的时候发现了一个问题,百思不得其解。
1、这一段代码输出的结果,我能看懂。
#include <iostream>
#include<string>
using namespace std;
int& test01() {
int a = 10;
return a;
}
int& test02() {
static int a = 10;
return a;
}
int main() {
int &a= test01();
//int &b = test02();
cout << a<< endl;
cout << a << endl;
//cout << b << endl;
//cout << b << endl;
system("pause");
return 0;
}
2、但是我把注释去掉以后,调用第二个函数
#include <iostream>
#include<string>
using namespace std;
int& test01() {
int a = 10;
return a;
}
int& test02() {
static int a = 10;
return a;
}
int main() {
int &a= test01();
int &b = test02();
cout << a<< endl;
cout << a << endl;
cout << b << endl;
cout << b << endl;
system("pause");
return 0;
}
怎么输出结果中有一个32758,a不是应该等于10吗?
请问这个是什么原因,请大佬解惑,谢谢,我是C++初学者。
第一段代码中连续两次输出的a值不同,你是怎么理解的呢?
test01()函数里的a是局部变量,每次函数被调用时创建,结束后销毁,&a=test01(),就是引用test01()里的局部变量a,当test01()返回后,局部变量a被销毁,用来存放a值的地方,随时会发生变化,所以输出的a可能每次都不一样。
test02()函数里的a是静态局部变量,它在程序生命周期内保持存在,所以输出都是10;
你把
int &b = test02();
cout << a<< endl;
这两行顺序交换一下,a就能输出10了吧?
如果是这样,那么就是一个问题,函数的临时变量地址是不靠谱的
这段代码我都编译不过去,返回非静态临时变量也是不靠谱的
返回临时变量引用,函数结束后变量立即释放。在第一段代码调用的时候,因为还没有其他代码覆盖原来临时变量的位置,所以第一次cout的值还没有变化,但是因为调用了cout,a位置的值就会被覆盖(因为他们放在栈区),第二次的cout时a已经变了。