脚本宝典收集整理的这篇文章主要介绍了【C++】 37_智能指针分析,脚本宝典觉得挺不错的,现在分享给大家,也给大家做个参考。
永恒的话题
编程实验: 内存泄漏
#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()
- 智能指针的使用军规: 只能用来指向堆空间中的对象或者变量
小结
- 指针特征操作符 ( -> 和 * ) 可以被重载
- 重载指针特征符能够使用对象代替指针
- 智能指针只能用于指向堆空间中的内存
- 智能指针的意义在于最大程序的避免内存问题
以上是脚本宝典为你收集整理的【C++】 37_智能指针分析全部内容,希望文章能够帮你解决【C++】 37_智能指针分析所遇到的问题。
本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。