【C++】 37_智能指针分析

22次阅读

共计 1385 个字符,预计需要花费 4 分钟才能阅读完成。

永恒的话题

内存泄漏(臭名昭著的 Bug)

动态申请堆空间,用完后不归还
C++ 语言中没有垃圾回收的机制
指针无法控制所指堆空间的生命周期

编程实验:内存泄漏
#include <iostream>
#include <string>

using namespace std;

class Test
{
private:
int i;
public:
Test(int i)
{
this->i = i;
}
int value()
{
return i;
}
~Test()
{
}
};

int main()
{
for(int i=0; i<5; i++) // 如果是 5000000 次呢?
{
Test* p = new Test(i);

cout << p->value() << endl;
}

return 0;
}
输出:
0
1
2
3
4

深度的思考

我们需要什么

需要一个特殊的指针
指针生命周期结束时主动释放堆空间
一块堆空间最多只能由一个指针表示(避免内存多次释放)
杜绝指针运算和指针比较(避免越界造成野指针)

智指针分析

解决方案

重载指针特征操作符 (-> 和 *)
只能通过类的成员函数重载
重载函数不能使用参数(只能定义一个重载函数)

编程实验:智能指针
#include <iostream>
#include <string>

using namespace std;

class Test
{
private:
int i;
public:
Test(int i)
{
cout << “Test(int i)” << endl;
this->i = i;
}
int value()
{
return i;
}
~Test()
{
cout << “~Test()” << endl;
}
};

class Poniter
{
private:
Test* m_pointer;
public:
Poniter(Test* p = NULL)
{
m_pointer = p;
}
Poniter(const Poniter& obj)
{
m_pointer = obj.m_pointer; // 所有权转接
const_cast<Poniter&>(obj).m_pointer = NULL;
}
Poniter& operator = (const Poniter& obj)
{
if(this != &obj)
{
delete m_pointer; // 所有权转接
m_pointer = obj.m_pointer;
const_cast<Poniter&>(obj).m_pointer = NULL;
}

return *this;
}
Test* operator -> ()
{
return m_pointer;
}
Test& operator * ()
{
return *m_pointer;
}
bool isNull()
{
return (m_pointer == NULL);
}
~Poniter()
{
delete m_pointer;
}
};

int main()
{
Poniter p1 = new Test(0);

cout << p1->value() << endl;

Poniter p2 = p1;

cout << p1.isNull() << endl;
cout << p2->value() << endl;

return 0;
}
输出:
Test(int i)
0
1
0
~Test()

智能指针的使用军规:只能用来指向堆空间中的对象或者变量

小结

指针特征操作符 (-> 和 *) 可以被重载
重载指针特征符能够使用对象代替指针
智能指针只能用于指向堆空间中的内存

智能指针的意义在于最大程序的避免内存问题

以上内容参考狄泰软件学院系列课程,请大家保护原创

正文完
 0