本文參考了
要搞清楚這個問題我們必須要先搞清楚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自然就會出錯了。
總結一下就是
- 當函數返回引用類型時,返回的是對象本身。
- 千萬不要返回局部對象的引用!千萬不要返回指向局部對象的指針!