我们的项目中就难避免的就是内存泄漏,内存泄漏就是动态申请堆空间,指针无法控制所指堆空间的生命周期,用完后不归还,有的编程语言有垃圾回收的机制,但是我们的C++语言没有垃圾回收机制,为了避免内存泄漏,我就需要一个特殊的指针,指针生命周期结束时主动释放堆空间,而且这一片堆空间最多只能由一个指针标识,还要避免指针运算和指针比较,,所以我们要提出一个解决方案满足上述要求
方案:
重载指针特征操作符(-> 和 *)
只能通过类的成员函数重载
重载函数不能使用参数
只能定义一个重载函数
先来看一个例子:
sice@sice:~$ cat test.cpp
#include <iostream>
#include <string>
using namespace std;
class Test
{
private:
int i;
public:
Test(int i)
{
cout<<"Test(int i)"<<endl;
this->i = i;
}
~Test()
{
cout<<"~Test()"<<endl;
}
int value()
{
return i;
}
};
class pointer
{
private:
Test *mp;
public:
pointer(Test* p = NULL)
{
mp = p;
}
Test* operator ->()
{
return mp;
}
Test& operator *()
{
return *mp;
}
~pointer()
{
delete mp;
}
};
int main()
{
for(int i=0;i<7;i++)
{
pointer p = new Test(i);
cout<<p->value()<<endl;
}
return 0;
}
结果;
Test(int i)
0
~Test()
Test(int i)
1
~Test()
Test(int i)
2
~Test()
Test(int i)
3
~Test()
Test(int i)
4
~Test()
Test(int i)
5
~Test()
Test(int i)
6
~Test()
可以看出我们定义了指针类,还重载操作符函数,实现指针的自动释放,这就是智能指针,是不是很强大!?,还可以改进,为了一片堆空间最多只能由一个指针标识,我们加入拷贝构造函数和操作符重载函数
例子:
#include <iostream>
#include <string>
using namespace std;
class Test
{
private:
int i;
public:
Test(int i)
{
cout<<"Test(int i)"<<endl;
this->i = i;
}
~Test()
{
cout<<"~Test()"<<endl;
}
int value()
{
return i;
}
};
class pointer
{
private:
Test *mp;
public:
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;
}
pointer(Test* p = NULL)
{
mp = p;
}
Test* operator ->()
{
return mp;
}
Test& operator *()
{
return *mp;
}
bool isNull()
{
return (mp == NULL);
}
~pointer()
{
delete mp;
}
};
int main()
{
pointer p = new Test(0);
cout << p->value() << endl;
pointer p2 ;//如果改为pointer p2 = p则调用拷贝构造函数
p2 = p;//
cout << p.isNull() << endl;
cout << p2->value() << endl;
return 0;
}
结果:
sice@sice:~$ ./a.out
Test(int i)
0
1
0
~Test()
这样我们就能使一片堆空间只能有一个指针指向,特别注意的是智能只能用来指向堆空间中的对象或者变量