C++函数的返回值——返回引用类型&非引用类型的区别
本文参考了
C++函数的返回值——返回引用类型&非引用类型
要搞清楚这个问题我们必须要先搞清楚return的时候发生了什么?
我们有一个类如下(不需要仔细看)
1
2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 |
#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的时候发生了什么?
1
2 3 4 5 |
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被析构掉了,但是和我没有啥关系了;
如果是返回的引用呢?
1
2 3 4 5 |
Student& fun2(int age, string name)
{ Student stu(age, name); // stu是局部变量,在函数执行完将会进行析构 return stu; } |
同理return的时候相当于发生了 Student& temp = stu;但是temp实际上是什么呢?是一个指针,指向stu的一个指针,而stu所在的空间随着fun2函数执行完就被回收了;这个时候我们再使用Student stu3 = fun2自然就会出错了。
总结一下就是
- 当函数返回引用类型时,返回的是对象本身。
- 千万不要返回局部对象的引用!千万不要返回指向局部对象的指针!
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· 【自荐】一款简洁、开源的在线白板工具 Drawnix