引用作为函数的返回值【C++学习笔记】

引用作为函数的返回值

特点

在内存中不产生返回值的副本;

如果函数的返回值是类A的对象,那么返回时,生成一个临时对象(相当于副本),并且这个临时对象在函数调用所在语句结束时就消亡。
如果函数的返回值是类A的引用,那么就不会生成一个临时对象,而是直接返回对象本身;

根据引用的特点,我们既可以把这种函数的调用作为右值,也可以利用函数返回的引用作为赋值表达式的左值;(具体见下面的例题)

语法

类型 &函数名(形参列表){ 函数体 }

例题

#include <iostream>
using namespace std;
class A {
public:
	int val;

	A(int v){
		val = v;
		cout << "constructor 1 called" << endl;
}
	A() {
		val = 123;
		cout << "constructor 2 called" << endl;
	}
	~A() {
		cout << "destructor called" << endl;
	}
	A GetObj() {
		return *this;
	}
};
int main()
{
	int m, n;
	A a;
	cout << a.val << endl;
	while (cin >> m >> n) {
		a.GetObj() = m;
		cout << a.val << endl;
		a.GetObj() = A(n);
		cout << a.val << endl;
	}
	return 0;
}

输入 2 3 4 5
输出结果如下:

constructor 2 called
123
2 3
constructor 1 called
destructor called
destructor called
123
constructor 1 called
destructor called
destructor called
123
4 5
constructor 1 called
destructor called
destructor called
123
constructor 1 called
destructor called
destructor called
123

但是如果把函数返回值改为引用

A& GetObj() {
		return *this;
	}

输出结果如下:

constructor 2 called
123
2 3
constructor 1 called
destructor called
2
constructor 1 called
destructor called
3
4 5
constructor 1 called
destructor called
4
constructor 1 called
destructor called
5

this指针

在GetObj函数中,由于题干限制了无参,不能直接返回;想到了隐藏的this指针;
*this即为当前成员函数作用的对象;
比如在主函数中写a.GetObj()时,this指针就指向了a;

返回*this,如果规定函数的返回值为引用,那么就相当于a.GetObj()返回了main函数中定义的a对象的别名,对它操作,会直接作用于a本身;
如果规定函数的返回值为对象本身,那么在返回时会生成一个临时对象,也就是a的副本,对a本身并不产生任何影响;该临时副本在函数调用语句结束之后消亡,调用析构函数;

哪些临时对象?

a.GetObj() = m;

如果返回值为引用,发生了什么?
第一步,类型转换构造函数让等号右边的整型m,转化为一个临时类A的对象;
第二步,对象a调用成员函数GetObj,返回值为a的引用;
第三步,第一步产生的临时对象的值赋给a的引用,相当于改变了a的val,变为m;
第四步,第一步生成的临时对象消亡,调用析构函数;

如果返回值是对象本身,又会发生什么?
会多一个临时对象的消亡,因为在函数GetObj结束时,副本会消亡。

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值