本文参考了
要搞清楚这个问题我们必须要先搞清楚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自然就会出错了。
总结一下就是
- 当函数返回引用类型时,返回的是对象本身。
- 千万不要返回局部对象的引用!千万不要返回指向局部对象的指针!
版权声明:本文为qq_40737025原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。