运算符重载++遇到的问题

来源:互联网 发布:设备远程连接用的端口 编辑:程序博客网 时间:2024/05/06 23:09

今天无事练习一下运算符重载,发现一个问题,暂时没解决。


class TestSimple{public:TestSimple(){cout << "TestSimple Constructor...!" << endl;pStr = new char[120];char *tmp = "I'm a heap var!";strncpy_s(pStr, 120, tmp, strlen(tmp));};TestSimple(TestSimple& obj){cout << "TestSimple Copy Constructor...!" << endl;pStr = new char[120];strncpy_s(pStr, 120, obj.pStr, strlen(obj.pStr));};~TestSimple(){if (pStr){cout << "TestSimple Destructor...!" << endl;delete[] pStr;pStr = nullptr;}};void SetNum(int iNum){num = iNum;}int GetNum() const{return num;}void PrintStr(){cout <<"pStr:"<< pStr << endl;}const TestSimple& operator ++ (){++num;return *this;}private:int num = 5;char *pStr;};int _tmain(int argc, _TCHAR* argv[]){TestSimple testSimpleOne;cout << "testSimpleOne:" << testSimpleOne.GetNum() << endl;++testSimpleOne;TestSimple testSimpleTwo;testSimpleTwo = ++testSimpleOne;cout << "testSimpleOne:" << testSimpleOne.GetNum() << endl;cout << "testSimpleTwo:" << testSimpleTwo.GetNum() << endl;}
错误:

运行时报错

问题1:

operator++返回引用,testSimpleTwo构造函数申请的内存不能得到释放,会泄露吗?
问题2:

由于testSimpleTwo指向的是testSimpleOne,testSimpleOne析构以后,堆内存申请的空间已经释放了,此时testSimpleTwo再去释放,会报错。


0 0
原创粉丝点击