从 C 向 C++ 进阶系列导航
1. 智能指针简介
为了解决可能发生的内存泄漏问题,C++ 提出了智能指针的概念。智能指针本质上为类对象,具备以下特征:
- 生命周期结束时,自动释放指向的内存空间。
- 只能指向堆空间的内存,不能指向其他空间的内存,因为只有堆空间内存的生命周期是可控的。
- 多个智能指针不能指向同一内存空间,防止重复对相同的内存释放。
- 智能指针不准许进行运算与比较。
2. 实现简单的智能指针
在智能指针类中,通过重载运算符 “->” 和 “*” 可以模拟实际指针的特性,且该运算符重载必须使用类成员函数的方式。同时,由于只能指向堆空间内容,涉及到系统资源的调用,因此需要使用深拷贝,必须实现拷贝构造函数与运算符 “=” 的重载函数。
- 实验:
class Test
{
int m_num;
public:
Test(int i)
{
cout << "Test(int i)" << endl;
this->m_num = i;
}
int value()
{
return m_num;
}
~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()
{
{ // Test(int i)
Pointer p1 = new Test(0);
} // ~Test()
Pointer p2 = new Test(3); // Test(int i)
Pointer p3 = p2;
cout << "p2.isNull = " << p2.isNull() << endl; // p2.isNull = 1
cout << "p3->value = " << p3->value() << endl; // p3->value = 3
return 0;
} // ~Test()
当然,以上的智能指针只能指向 Test 类型的堆内存,具有局限性。C++ 标准提供了模版来实现完整的智能指针(后续讲解)。