我是新手,向各位大神请教一个问题:
用元素接收返回的局部引用,会出现内存错误,但用引用接收返回的局部引用,没有问题,是什么原因?谢谢各位大神解答
因为你定义了拷贝构造函数
#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
这是输出
局部对象,当这个方法执行完毕后, 就销毁了,如果你是new了一个指针,只要你没有delete,他就存在,所以后面那种情况没报错
http://blog.sina.com.cn/s/blog_4b34c6790100pm2d.html
你需要定义一个拷贝构造函数。这样才能把堆栈上的对象传回来。
#include <stdio.h>
class A
{
public:
int x;
A()
{
}
//*
A(A& a)
{
x = a.x;
printf("A(A& a)\n", a.x);
}
//*/
};
A getA()
{
A a;
a.x = 123;
return a;
}
int main(int argc, char* argv[])
{
A a = getA();
printf("%d\n", a.x);
return 0;
}
我的代码如下:
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;
}
请教大神这是什么问题,谢谢
c++语法的。引用会延长临时对象生命期。而临时变量会释放。后面访问就会出错了
因为引用了不再存在的对象,所以会出问题。这是理论上的原因。
根本原因是,
实现中,引用是指针的另一种存在方式
实现中,引用往往只是封装了指针,具体应用的时候,和使用指针类似。
引用不存在的对象,等同于野指针解引用
根据 caozhy的答案是定义拷贝函数的原因,我测试了下,发现返回引用只存在Teacher::Teacher(const Teacher &t2) {这行代码,是不是返回的引用不能当参数传递,还是其他原因?谢谢,指教!
1、Teacher &t2 = t1.retT();
2、Teacher t2 = t1.retT();
t1.retT()返回的是一个Teacher类变量的引用,在retT函数内部创建了一个Teacher变量,在返回时会进行复制,返回的类型相当于一个类变量的指针,第1行正确的定义了指针类型变量用于接收返回值,而第二行定义的变量类型与返回类型不匹配。