c++自动回收的问题,对象从子函数返回后还能生效
- C/C++ code
#include "stdafx.h"#include <iostream>using namespace std;class A{ int v; char* name;public: A(char* n){ this->name = n; v=3; cout << name << "-->create " << endl; } ~A(){ cout << name << "-->Destroy " << endl; } void setValue(int v){ this->v =v; } int getValue(){ return v; }}; A getA(){ A a("getA()") ;//= new A("getA()"); a.setValue(1999); A* b =&a; return a;}int _tmain(int argc, _TCHAR* argv[]){ A c = getA(); A *d =(&c); c.setValue(6000); cout << "c.getValue:" << c.getValue() << endl; //这里正常 delete d; //这里就出错了 return 0; }输出结果:
getA()-->create
getA()-->Destroy
c.getValue6000
getA()-->Destroy
[解决办法]
查一查 拷贝构造函数
[解决办法]
算是半自动的垃圾回收机制
楼主搞懂了destructor怎么使用后
可以google一下STL和smart pointer
在现代C++编程中,我们几乎都不会呼叫delete的啦
资源有99%以上的情况都交给STL和smart pointer管理了(使用Qt时除外)
[解决办法]
[解决办法]
只有new出来的对象(堆上面分配的对象)才能delete....
直接"A c;"这样的代码是在栈上分配的,不能手动调用delete。
堆上分配/析构方法:
A* a = new A;
delete a;
栈上分配方法:
A a;
栈上分配的对象,只要出了花括号自动会析构,不用担心内存泄漏,但是这不算自动回收机制。
{
A a; //-->构造了A对象
} //-->花括号结尾析构了A对象
你的"getA();"返回的是A对象的一个拷贝,这个拷贝也是在栈上分配的。