C++内存泄露主要发生在浅拷贝阶段:
例如
#include<iostream>
#include<string>
#include<cstring>
#include<memory>
using namespace std;
class A
{
private:
char *m;
size_t n;
public:
A(size_t n=1)
{
cout<<"i want to creat it"<<endl;
m=new char[n];
this->n=n;
}
~A()
{
cout<<"i ready to destory it"<<endl;
delete m;
}
char *getbuf()
{
return m;
}
};
void foo()
{
auto_ptr<A>p(new A);
auto_ptr<A>b=p;
auto_ptr<A>c(new A);
c=p;
}
int main()
{
A a(1);
A b=a;
//b=a;
}
由于发生了浅拷贝,所以程序退出的时候,就中断了,因为同一内存析够了2次。至于为什么同一对象析够2次就会中断,是因为已经析够的对象所占据的内存已经还给操作系统,再次访问时,就报错了。
为此,c++创造了智能指针,但是智能指针都有缺陷。
1.auto_ptr:确定是在copy时候,会释放所有权,而且不可以用于数组。
2.scoped_ptr克服了auto_ptr在复制的时候,释放所有权的缺点。
3.scoped_array 是scoped_ptr的扩展形式,可以用于数组。
4.share_ptr可以拷贝,可复制的智能指针,但是不可以循环引用。
5,.wear_ptr指针检测share_ptr是否循环引用。