编译环境VS2010,32位
测试代码1:
class TestClass {
public:
TestClass(void){};
TestClass(int i) {m_A = i; m_B = i + 1; m_C = i + 2; m_D = i + 3;};
~TestClass(){printf("release %d %d %d %d\n",m_A, m_B, m_C, m_D);};
void Input(int i){m_A = i + 100; m_B = i + 101; m_C = i + 102; m_D = i + 103;};
TestClass get(int i){
TestClass t;
t.Input(i);
return t;
};
TestClass& operator = (TestClass& n) {printf("copy value\n");m_A = n.m_A; m_B = n.m_B; m_C = n.m_C; m_D = n.m_D;return *this;};
public:
int m_A;
int m_B;
int m_C;
int m_D;
};
void main()
{
TestClass a(10);
TestClass b(20);
TestClass c(30);
printf("start\n");
c = a.get(5);
printf("end\n");
printf("C = %d %d %d %d\n", c.m_A, c.m_B, c.m_C, c.m_D);
}
关键代码:
TestClass get(int i){
TestClass t;
t.Input(i);
return t;
};
c = a.get(5);
测试结果:
start
release 105 106 107 108
copy value
release 105 106 107 108
end
C = 105 106 107 108
release 105 106 107 108
release 20 21 22 23
release 10 11 12 13
请按任意键继续. . .
分析:
1、t返回之前,get函数结束局部变量,执行t的析构函数;
2、返回出来之后,执行拷贝赋值;
3、拷贝完了之后,再执行t的拷贝赋值函数;
4、c的值被改变成局部变量对象的值。
测试代码2:
TestClass& get(int i){
TestClass t;
t.Input(i);
return t;
};
c = a.get(5);
测试结果:
start
release 105 106 107 108
copy value
end
C = -858993460 -858993460 -858993460 -858993460
release -858993460 -858993460 -858993460 -858993460
release 20 21 22 23
release 10 11 12 13
请按任意键继续. . .
分析:
1、t返回之前,get函数结束局部变量,执行t的析构函数;
2、返回出来之后,执行拷贝赋值;
3、c的值被改变成乱码
测试代码3:
TestClass& get(int i){
TestClass* t = new TestClass();
t->Input(i);
return *t;
};
c = a.get(5);
测试结果:
start
copy value
end
C = 105 106 107 108
release 105 106 107 108
release 20 21 22 23
release 10 11 12 13
请按任意键继续. . .
分析
1、返回出来执行拷贝赋值;
2、C的值被改变了
成员函数申请的内存TestClass* t = new TestClass();,
没有释放,内存泄漏