由于局部的对象或变量是在栈中,当函数调用结束的时候,其会自动释放掉,你这样传递数据,会得到垃圾值!看下面的测试:
测试1
复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16#include "stdafx.h" #include<iostream> using namespace std; int & reference_test() { int a=5; return a; } int _tmain(int argc, _TCHAR* argv[]) { int &reference_a=reference_test(); cout<<reference_a<<endl; system("pause"); return 0; }
测试结果:
我们发现其结果是正确的,不是说会得到垃圾值吗,这是什么原因呢?分析知:局部变量的值留在栈里,然而栈没有被改动,所以才引用局部变量可以得到正确。一般来说,系统不会主动清理栈,栈什么时候改动呢,比如下一次函数调用时,再看下面的例子:
测试2
复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20#include "stdafx.h" #include<iostream> using namespace std; int & reference_test() { int a=5; return a; } void f() { } int _tmain(int argc, _TCHAR* argv[]) { int &reference_a=reference_test(); f(); cout<<reference_a<<endl; system("pause"); return 0; }
由于在传回引用后,又再一次的使用了栈(调用了void f()函数),此时我们就得不到正确值了。因为这里reference_a和函数reference_test() 中a共享一块内存区域,当栈区被清理时候,其就会得到垃圾值。
测试3
复制代码
这里测试结果是正确的,这是为什么呢?因为这里reference_a是i_temp 的引用,它和i_temp 是共享同一块内存区域,在调用reference_test()函数时,相当于将引用变量的值赋给了i_temp,因此值也就被保留下来了。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22#include "stdafx.h" #include<iostream> using namespace std; int & reference_test() { int a=5; return a; } void f() { } int _tmain(int argc, _TCHAR* argv[]) { int i_temp=10; int &reference_a=i_temp; reference_a=reference_test(); f(); cout<<reference_a<<endl; system("pause"); return 0; }
因此 ,尽量不要尝试传回引用,可能会存在潜在的错误。
最后
以上就是务实糖豆最近收集整理的关于关于返回对象或变量的引用(reference)的问题的全部内容,更多相关关于返回对象或变量内容请搜索靠谱客的其他文章。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复