一、典型的一个内存泄露的代码例子
#include<iostream>
using namespace std;
class A
{
public:
A (int i){this->i=i;cout<<"costr"<<endl;}
int getI();
A(A&a)
{
this->i=a.i;
cout<<"copy"<<endl;
}
~A(){cout<<"destory"<<endl;}
private:
int i;
};
A::getI()
{
return this->i;
}
A fuct()
{
A *a = new A(12);
return *a;
}
void main()
{
A *a = &fuct();
cout<<a->getI()<<endl;
}
我们可以看到只调用了一次析构函数,由于在fuct函数中,使用了new 关键字创建了一个堆中空间,在函数运行结束时,
返回的是一个副本,调用的复制构造函数返回,因此在fuct函数中创建的一个堆中空间就无法释放,因此出现了内存泄露。
二、避免出现内存泄露的改进
#include<iostream>
using namespace std;
class A
{
public:
A (int i){this->i=i;cout<<"costr"<<endl;}
int getI();
A(A&a)
{
this->i=a.i;
cout<<"copy"<<endl;
}
~A(){cout<<"destory"<<endl;}
private:
int i;
};
A::getI()
{
return this->i;
}
A &fuct()
{
A *a = new A(12);
return *a;
}
void main()
{
A &a = fuct();
A *p=&a;
delete p;
cout<<a.getI()<<endl;
}
这样就可以避免内存的泄露,但是会出现一个致命的错误,就是会出现一个空的引用存在。
三、哪里创建哪里删除原则
在使用,函数中如果是要使用返回创建的指针,可以在调用的该方法的地方前创建,调用结束后,在释放该快内存。
修改代码如下:
#include<iostream>
using namespace std;
class A
{
public:
A (int i){this->i=i;cout<<"costr"<<endl;}
int getI();
void setI(int x)
{
this->i=x;
}
A(A&a)
{
this->i=a.i;
cout<<"copy"<<endl;
}
~A(){cout<<"destory"<<endl;}
private:
int i;
};
A::getI()
{
return this->i;
}
A &fuct(A &a)
{
a.setI(56);
return a;
}
void main()
{
A *a= new A(15);
fuct(*a);
cout<<a->getI()<<endl;
delete a;
}
就可以做到在函数中不进行创建空间,在main函数中创建,在main函数中释放。