用元素接收返回的局部引用,会出现内存错误,但用引用接收返回的局部引用,没有问题,是什么原因?谢谢各位大神解答
版权声明:本文内容由阿里云实名注册用户自发贡献,版权归原作者所有,阿里云开发者社区不拥有其著作权,亦不承担相应法律责任。具体规则请查看《阿里云开发者社区用户服务协议》和《阿里云开发者社区知识产权保护指引》。如果您发现本社区中有涉嫌抄袭的内容,填写侵权投诉表单进行举报,一经查实,本社区将立刻删除涉嫌侵权内容。
#include <stdio.h>
#include <iostream>
using namespace std;
class Teacher
{
public:
Teacher(int a);
Teacher(const Teacher &t2);
Teacher& retT();
Teacher(int a,int b);
~Teacher();
int a;
int b;
};
Teacher::Teacher(int a) {
this->a = a;
cout << "执行Teacher构造函数 \n a=" << this->a << endl;
}
Teacher::Teacher(int a,int b) {
this->a = a;
this->b = b;
cout << "执行Teacher构造函数 \n this->a=" << this->a << ";this->b=" << this->b<< endl;
}
Teacher::Teacher(const Teacher &t2) {
this->a = t2.a;
cout << "执行Teacher的copy函数 t2.a=" << t2.a << endl;
}
Teacher::~Teacher() {
cout << "执行Teacher析构函数 this->=" << this->a << endl;
}
Teacher& Teacher::retT() {
Teacher t1(120);
Teacher &t2 = t1;
return t2;
}
void main() {
Teacher t1(12);
Teacher &t2 = t1.retT();
//Teacher t2 = t1.retT();
cout << "main05中的t2.a=" << t2.a << endl;
}
这么写不会调用拷贝构造函数
执行Teacher构造函数
a=12
执行Teacher构造函数
a=120
执行Teacher析构函数 this->=120
main05中的t2.a=120
执行Teacher析构函数 this->=12
Press any key to continue
这是输出