您的位置:首页 > 其它

智能指针原理理解 和 ->运算符的重载

2019-03-14 23:32 120 查看

一个内存泄漏的实例:

[code]#include<iostream>

void Func(int *p)
{
int *ptmp = new int;
if (p == NULL)
{
throw std::exception("p is null!");
}
*ptmp = *p;
delete ptmp;
}

int main()
{
while (true)
{
try{
Func(NULL);
}
catch (std::exception& error)
{
std::cout << error.what() << std::endl;
}
}
return 0;
}

        我们给Func函数的实参传入了一个NULL,当进入到Func函数内的 if 判断时,抛出异常,返回函数的调用点,但是Func函数没有释放 ptmp 所指向的内存,导致了内存泄露,这种问题一般是很难处理的,因此有了智能指针来帮助我们解决这个问题。

对智能指针的分析:

代码如下:

[code]#include<iostream>

class SmartPtr
{
public:
SmartPtr(int *p) :ptr(p){}
SmartPtr()
{
delete ptr;
ptr = NULL;
}
private:
int *ptr;
};

int main()
{
int *p = new int;
delete p;

SmartPtr sp = new int; //相比上一行,不用手动释放,由对象sp的析构函数来完成释放这个操作
return 0;
}

->运算符的重载(->是单目运算符):

->运算符三步:  

        <1>       sp.operator->()   //对象先调用 operator->() 函数

        <2>       Test*   ptmp    //由第一步得到

        <3>       ptmp->Show()  //通过指针来调用函数

[code]#include<iostream>
using namespace std;

class Test
{
public:
Test(int val) :data(val){}

void Show()
{
std::cout << data << std::endl;
}
private:
int data;
};

class SmartPtr
{
public:
SmartPtr(Test *p)
{
ptr = p;
}
~SmartPtr()
{
delete ptr;
}
Test& operator*()
{
return *ptr;
}
Test* operator->()
{
return ptr;
}
private:
Test *ptr;
};

int main()
{

Test *p = new Test(10);
p->Show(); //通过指针就可以释放空间
delete p;

SmartPtr sp = new Test(20);
sp->Show(); //重载运算符->后, 则变为ptmp->Show(),ptmp为Test* 类型
return 0;
}

 

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: