如果返回值类型为引用或者指针,一定要注意,返回的值在函数调用完成后仍然存在

如果返回值类型是reference 或者pointer,那么这是一定要是注意,函数调用完后,被返回的变量要仍然存在,不能被编译器撤销。

 1 int* fun1(){
 2 
 3     int i = 10;
 4     return &i;
 5 }
 6 
 7 int& fun2(){
 8 
 9     int i = 10;
10     return i;
11 
12 }
13 void test2(){
14     
15     int* pi = fun1();
16     cout <<endl;
17     cout << *pi << endl;
18     
19     
20     int& ri = fun2();
21     cout << endl;
22     cout << ri << endl;
23     
24 
25 }
26 
27 int main(int argc, char** argv){
28     test2();
29     system("pause");
30     return 0;
31 
32 }

无论是fun1还是fun2中,返回的变量都是一个局部变量,也没有用static修饰,所以当fun1与fun2调用完成后,被返回的变量i就会被编译器撤销,也就是不再存在,这是无论是指针还是引用,都指向了一个无用的空间。下面是代码运行结果

原文地址:https://www.cnblogs.com/cplinux/p/5582166.html