内存泄漏的一个重要的原因是你忘记了在你的class或者function中使用了delete操作符。
class.h
#ifndef _CLASSH_H
#define _CLASSH_H
#include <iostream>
using namespace std;
class Buddy{
public:
Buddy(){
a = 0;
}
~Buddy(){
cout<<"Buddy is destroyed.."<<endl;
}
void setA(int newa){
a = newa;
}
int getA(){
return a;
}
private:
int a;
};
class Brother{
public:
Brother(){
buddy = new Buddy();
}
~Brother(){
if(buddy){
delete buddy;
buddy = NULL;
cout<<"Brogher---buddy destroyed"<<endl;
}
}
void setBuddy(Buddy *newBuddy){
buddy = newBuddy;
}
Buddy *getBuddy(){
return buddy;
}
private:
Buddy *buddy;
};
#endif
test.h
#include "classh.h"
#include <iostream>
using namespace std;
Buddy *testReturnPointer(int num){
Buddy *result = new Buddy();
result->setA(num);
return result;
}
Brother *testPointerInsideClass(int num){
Brother *bro = new Brother();
Buddy *b = new Buddy();
b->setA(num);
bro->setBuddy(b);
return bro;
}
Buddy &getReference(int num){
static Buddy bud;
bud.setA(num);
return bud;
}
test.cpp
#include "test.h"
#include <iostream>
using namespace std;
int main(){
Buddy *buddy = testReturnPointer(90);//-----------------1
Brother *bro = testPointerInsideClass(45);//-------------2
Buddy bud =getReference(44);
cout<< bud.getA()<<endl;
Buddy bud1 =getReference(464);
cout<< bud1.getA()<<endl;
delete buddy;//-------------------------------------------------1'
delete bro;//-----------------------------------------------------2'
return 0;
}
如果你是在其他函数中返回指针,如testReturnPointer()-----1;然后在其他函数或者main里面调用。如果你忘记了写与1对应的delete buddy----------1'那么buddy对应的内存空间就不会被释放。同样testPointerInsideClass()----2也返回的是一个Brogher的指针,而Brother这个类又包含了Buddy的指针变量。这个时候也需要注意在Brother析构函数中把已经分配给Buddy指针变量的空间给收回。即:
~Brother(){
if(buddy){
delete buddy;
buddy = NULL;
cout<<"Brogher---buddy destroyed"<<endl;
}
}
由于C++没有Java那样的垃圾回收机制。你必须这样手动释放掉你在程序中new出来的空间。如果对指针不熟悉,或者经常忘记,一个简单的方法可以把指针或者变量设置成static,由于这样整个程序只有一份地址空间,而且其对象在程序结束时自动调用了析构函数,所以不会有泄漏的问题,如:
Buddy &getReference(int num){
static Buddy bud;
bud.setA(num);
return bud;
}
更多的关于内存泄漏和解决方法,请参考:http://www.codersource.net/c++_memory_leaks.aspx