C++函数中返回引用和对象的区别

本文参考了

C++函数的返回值——返回引用类型&非引用类型

要搞清楚这个问题我们必须要先搞清楚return的时候发生了什么?

我们有一个类如下(不需要仔细看)

#define _CRT_SECURE_NO_WARNINGS
#include<iostream>
#include<string>
using namespace std;
static int i = 0;
class Student
{
private:
	int age;
	string name;
public:
	/*
	构造函数
	*/
	Student(int age, string name)
	{
		this->age = age;
		this->name = name;

		cout << "构造函数" << endl;
	}
	/*
	无参构造函数
	*/
	Student() { cout << "无参构造函数" << endl; }
	/*
	拷贝构造函数
	*/
	Student(const Student & stur)
	{
		age = stur.age;
		name = stur.name;
		cout << "拷贝构造函数" << endl;
	}
	/*
	析构函数
	*/
	~Student()
	{
		cout << "析构函数" << endl;

	}
	void print()
	{
		cout << age << endl;
	}
};

以下方法在return的时候发生了什么? 

Student fun(int age, string name)
{
	Student stu(age, name);   // stu是局部变量,在函数执行完将会进行析构
	return stu;//会存在Student temp = stu,在主调函数中如果有变量接受  temp的话就不会立刻释放
}

return的时候相当于发生了   Student temp = stu;返回的实际上是temp;也就是将stu这一整个对象拷贝给了temp;

我们调用  Student stu2 = fun(10,“张三”);这一瞬间就是将temp转正为stu2;这个时候stu被析构掉了,但是和我没有啥关系了;

 

如果是返回的引用呢?

Student& fun2(int age, string name)
{
	Student stu(age, name);   // stu是局部变量,在函数执行完将会进行析构
	return stu;
}

同理return的时候相当于发生了   Student& temp = stu;但是temp实际上是什么呢?是一个指针,指向stu的一个指针,而stu所在的空间随着fun2函数执行完就被回收了;这个时候我们再使用Student stu3 = fun2自然就会出错了。

总结一下就是

  • 当函数返回引用类型时,返回的是对象本身。
  • 千万不要返回局部对象的引用!千万不要返回指向局部对象的指针!
  • 3
    点赞
  • 13
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值