1 C++中的指针特征操作符重载
1.1 指针特征操作符重载
指针特征操作符重载:
- 可以重载指针特征操作符(->和*)。
- 只能通过类对的成员函数重载。
- 重载函数不能使用参数。
- 只能定义一个重载函数。
- 重载指针特征符能够使用对象代替指针。
1.2 使用指针特征操作符重载实现智能指针
内存泄漏(臭名昭著的bug):
- 动态申请堆空间,用完不归还。
- C++语言没有垃圾回收的机制。
- 指针无法控制所指堆空间的生命周期。
我们需要什么:
- 需要一个特殊指针。
- 指针生命周期结束时主动释放堆空间。
- 一片堆空间最多只能由一个指针标识。
- 杜绝指针运算和指针比较。
智能指针的使用军规:只能用来指向堆空间中的对象或者变量。智能指针的意义在于最大程度的避免内存问题。
智能指针的实现:
#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;
}
参考资料:
本文深入探讨了C++中智能指针的实现原理,通过操作符重载来控制堆空间的自动释放,有效防止内存泄漏。文章详细介绍了如何重载指针特征操作符,并提供了一个具体的智能指针实现示例。
259

被折叠的 条评论
为什么被折叠?



