函数返回值为引用类型

142 篇文章 0 订阅

函数返回值为引用类型

?
#include<iostream>
#include<string>
#include<fstream>
using  namespace  std;
ofstream out( "test.out" );
class  A
{
         public :
         string id;
         A(string iid= "" ):id(iid){out<< "A(),iid=" <<iid<<endl;}
         A( const  A& a) {id=a.id+ "copy" ;out<< "A(const A& a),iid=" <<id<<endl;}
         A& operator=( const  A& rv)
         {
                 id=rv.id;
                 return  * this ;
         }
         A f1(){ return  * this ;}
         A& f2(){ return  * this ;}
         A& f3(){A* pb= new  A; return  *pb;}
 
};
A& f()
{
         A a( "a" );
         cout<< "in f():" <<&a<<endl;
         return  a;
}
int  main()
{
         A a( "a" );
         cout<< "&a:" <<&a<<endl;
         cout<< "f1():" <<&(a.f1())<<endl;
         cout<< "f2():" <<&(a.f2())<<endl;
         A b=a.f2();
         cout<< "&b:" <<&b<<endl;
         cout<< "f3():" <<&(a.f3())<<endl;
         cout<< "in main f():" <<&(f())<<endl;
         return  0;
 

  

从输出可以看出:

对象a的起始地址与函数f2()的返回值地址相同,f2()的返回为引用;

 

 

对象b的地址与对象a的地址不同,两个对象在内存中占有独立的空间,利用返回的引用类型初始化b,而不是在内存中再生成一个a对象的副本,然后再初始化b;

 

对象a的起始地址与函数f1()的返回值地址不相同,f1()的返回不是引用,在内存中生成了一个对象a的副本;

函数f()返回局部对象的引用是会有警告的,因为函数返回后,局部变量的内存将被释放,选用这个例子只是为了测试编译器在返回是临时对象的引用时是怎样处理的。可以看出,即使是返回一个临时对象的引用,编译器也不会为了确保安全而生成一个临时对象返回。

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值