下面看一段内存泄漏的代码:

#include <iostream>
#include <string>
using namespace std;
class Test
{
int i;
public:
Test(int i)
{
this->i = i;
}
int value()
{
return i;
}
~Test()
{
}
};
int main()
{
for(int i=0; i<5; i++)
{
Test* p = new Test(i);
cout << p->value() << endl;
}
return 0;
}
输出结果如下:
解决方案
下面看一段智能指针的使用示例:
#include <iostream>
#include <string>
using namespace std;
class Test
{
int i;
public:
Test(int i)
{
cout << "Test(int i)" << endl;
this->i = i;
}
int value()
{
return i;
}
~Test()
{
cout << "~Test()" << endl;
}
};
class Pointer
{
Test* mp;
public:
Pointer(Test* p = NULL)
{
mp = p;
}
Pointer(const Pointer& obj)
{
mp = obj.mp;
const_cast<Pointer&>(obj).mp = NULL;
}
Pointer& operator = (const Pointer& obj)
{
if (this != &obj)
{
delete mp;
mp = obj.mp;
const_cast<Pointer&>(obj).mp = NULL;
}
return *this;
}
Test* operator -> ()
{
return mp;
}
Test& operator * ()
{
return *mp;
}
bool isNull()
{
return (mp == NULL);
}
~Pointer()
{
delete mp;
}
};
int main()
{
Pointer p1 = new Test(0);
cout << p1->value() << endl;
Pointer p2 = p1;
cout << p1.isNull() << endl;
cout << p2->value() << endl;
return 0;
}
输出结果如下:
注意这两行代码的含义,
mp = obj.mp; const_cast<Pointer&>(obj).mp = NULL;
表明当前对象的成员指针指向初始化对象的成员指针所对应的堆空间,这就两个智能指针对象指向了同一片堆空间,然后 const_cast<Pointer&>(obj).mp = NULL; 表明初始化对象把自己管理的堆空间交给当前对象。这就完成了前面说的“一片堆空间最多只能由一个指针标识”。
智能指针使用的军规:只能用来指向堆空间中的对象或者变量