智能指针
永恒的话题
内存泄漏
动态申请堆空间,用完后不归还 C++语言中没有垃圾回收的机制 指针无法控制所指堆空间的生命周期 我们需要什么
需要一个特殊的指针 指针生命周期结束时主动释放堆空间 一片堆空间最多只能由一个指针标识 杜绝指针运算和指针比较 解决方案
重载指针特征操作符(->
和*
) 只能通过类的成员函数重载 重载函数不能使用参数 只能定义一个重载函数
智能指针的创建和使用
#include <iostream>
using namespace std;
class Test
{
private:
int i;
public:
Test(int i);
int value();
~Test();
};
Test::Test(int i)
{
this->i = i;
}
int Test::value()
{
return i;
}
Test::~Test()
{
}
class Pointer
{
private:
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);
Test* operator -> ();
Test& operator * ();
bool isNull();
~Pointer();
};
Pointer& Pointer::operator = (const Pointer& obj)
{
if(this != &obj){
delete mp;
mp = obj.mp;
const_cast<Pointer&>(obj).mp = NULL;
}
return *this;
}
Test* Pointer::operator -> ()
{
return mp;
}
Test& Pointer::operator * ()
{
return *mp;
}
bool Pointer::isNull()
{
return (mp==NULL);
}
Pointer::~Pointer()
{
delete mp;
cout<<"~Test()"<<endl;
}
int main(int argc, char const *argv[])
{
Pointer p1 = new Test(0);
cout<<p1->value()<<endl;
Pointer p2 = p1;
cout<<p1.isNull()<<endl;
cout<<p2->value()<<endl;
return 0;
}
注意:智能指针只能用来指向堆空间中的对象或者变量
小结
指针特征操作符(->
和 *
)可以被重载 重载指针特征符能够使用对象代替指针 智能指针只能用于指向堆空间中的内存 智能指针的意义在于最大程度的避免内存问题