函数返回引用的注意事项

来源:互联网 发布:淘宝网店域名怎么改 编辑:程序博客网 时间:2024/06/09 12:34


转载
http://baimafujinji.blog.51cto.com/907111/195792

引用作为函数的返回值时,函数的返回值可以理解为函数返回了一个变量(事实上,函数返回引用时,它返回的是一个指向返回值的隐式指针),因此,值为引用的函数可以用作赋值运算符的左操作数。另外,用引用返回一个函数值的最大好处是,在内存中不产生被返回值的副本。


[cpp] view plaincopyprint?在CODE上查看代码片派生到我的代码片
  1. #include<iostream>  
  2.     using namespace std;  
  3.    
  4. int &func()  
  5. {  
  6.     static int num = 0;  
  7.         return ++num;  
  8. }  
  9.      
  10. int main()  
  11. {  
  12.         int i;  
  13.    
  14.         for(i=0; i<5; i++)  
  15.             cout<<func()<<'\t';  
  16.         cout<<endl;  
  17.    
  18.         func()=10;  
  19.    
  20.         for(i=0; i<5; i++)  
  21.             cout<<func()<<'\t';  
  22.         cout<<endl;  
  23. }  
  24.   
  25. /* 
  26. $ g++ -o test test1.cpp 
  27. $ ./test  
  28. 1   2   3   4   5    
  29. 11  12  13  14  15   
  30.  
  31. */  





不能返回函数内部动态分配的内存的引用。虽然不存在局部变量的被动销毁的问题,但是在此种情况下,仍然存在一些问题。例如,被函数返回的引用只是作为一个临时变量出现,而没有被赋予一个实际的变量,那么这个引用所指向的由new分配的空间就无法被释放,从而造成内存泄漏问题。
举例如下:
[cpp] view plaincopyprint?在CODE上查看代码片派生到我的代码片
  1. #include <iostream>  
  2.   
  3.   
  4. int *& fun()  
  5. {  
  6.     int *p = new int(1);  
  7.     return p;  
  8. }  
  9.   
  10. int main()  
  11. {  
  12.   
  13.     int *a;  
  14.     a = fun();  
  15.   
  16. }  

$ g++ -o test2 test2.cpp
test2.cpp: In function ‘int*& fun()’:
test2.cpp:8:7: warning: reference to local variable ‘p’ returned [-Wreturn-local-addr]
  int *p = new int(1);
       ^


 
最后,可以返回类成员的引用,但最好是const常量。这是因为当对象的属性是与某种业务规则相关联的时候,其赋值常常与某些其它属性或者对象的状态有关,于是有必要将赋值操作封装在一个业务规则当中。如果其它对象可以获得该属性的非常量引用,那么对该属性的单纯赋值就会破坏业务规则的完整性。
0 0
原创粉丝点击