智能指针为了解决内存泄漏的问题而诞生
内存泄漏: (1)动态申请堆空间,用完后不归还 (2)C++语言中没有垃圾回收的机制 (3)指针无法控制所指堆空间的生命周期
编程实验:内存实验
#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;
}
深度思考: 我们需要什么? (1)需要一个特殊的指针 (2)指针生命周期结束时主动释放堆空间 (3)一片堆空间最多只能由一个指针表示 (4)杜绝指针运算和指针比较 解决方案 (1)重载指针特征操作符(->和)* (2)只能通过类的成员函数重载 (3)重载函数不能使用参数 (4)只能定义一个重载函数
编程实验:智能指针
#include <iostream>
#include <string>
using namespace std;
class Test
{
int i;
public:
Test(int i)
{
this->i = i;
cout << "Test" << endl;
}
int value()
{
return i;
}
~Test()
{
cout << "~Test()" << endl;
}
};
class Pointer
{
Test* mp;
public:
Pointer(Test* p = NULL)
{
mp = p;
cout << "Pointer" << endl;
}
Test* operator -> ()
{
return mp;
}
Test& operator * ()
{
return *mp;
}
~Pointer()
{
delete mp;
cout << "~Pointer()" << endl;
}
};
int main()
{
for(int i = 0; i < 5; i++)
{
Pointer 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)
{
this->i = i;
cout << "Test" << endl;
}
int value()
{
return i;
}
~Test()
{
cout << "~Test()" << endl;
}
};
class Pointer
{
Test* mp;
public:
Pointer(Test* p = NULL)
{
mp = p;
cout << "Pointer" << endl;
}
Pointer(const Pointer& obj)
{
mp = obj.mp;
const_cast<Pointer&>(obj).mp = NULL;
cout << "Pointer(const Pointer& obj)" << endl;
}
Pointer& operator=(const Pointer& obj)
{
if(this != &obj)
{
delete mp;
mp = obj.mp;
const_cast<Pointer&>(obj).mp = NULL;
cout << "Pointer& operator=" << endl;
}
return *this;
}
bool isNULL()
{
return (mp == NULL);
}
Test* operator -> ()
{
return mp;
}
Test& operator * ()
{
return *mp;
}
~Pointer()
{
delete mp;
cout << "~Pointer()" << endl;
}
};
int main()
{
Pointer p1 = new Test(0);
cout << p1->value() << endl;
Pointer p2 = p1;
cout << p1.isNULL() << endl;
cout << p2->value() << endl;
return 0;
}
智能指针使用军规: 只能用来指向堆空间中的对象或者变量 小结: (1)重载智能指针特征符能够使用对象代替指针 (2)智能指针只能用于指向堆空间中的内存
|