一、永恒的话题
1、内存泄漏(臭名昭著的Bug)
- 动态申请堆空间,用完后不归还
- C++中语言中没有垃圾回收的机制
- 指针无法控制所指堆空间的生命周期(指针挂了,但内存空间依然存在)
示例:内存泄漏
#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;
}
2、深度的思考
我们需要这么解决这个问题?
- 需要一个特殊的指针
- 指针生命周期结束时主动释放堆空间(使用对象代替指针)
- 一片堆空间最多只有一个指针标识(重载拷贝构造函数和赋值操作符)
- 杜绝指针运算和指针比较
解决方案:
- 重载指针特征操作符(->和 *)
- 只能通过类的成员函数重载
- 重载函数不能使用参数
- 只能定义一个重载函数
示例:智能指针
#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;
}
注意:在重载赋值操作符时返回值一定是引用,可以连续赋值,参数一定是const引用,考虑自赋值的情况
小结
- 指针操作符(->和*)可以被重载
- 重载指针特征符能够使用对象代替指针
- 智能指针只能用于指向堆空间的内存
- 智能指针的意义在于最大程度避免内存问题