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自然就会出错了。

总结一下就是

  • 当函数返回引用类型时,返回的是对象本身。
  • 千万不要返回局部对象的引用!千万不要返回指向局部对象的指针!
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章