37、智能指针分析

内存泄漏:动态申请堆空间,用完后不归还,c++中没有垃圾回收机制,指针无法控制所指堆空间的生命周期。

#include <iostream>
#include <string>
using namespace std;
class Test
{
    int i;
public:
    Test(int i)
    {
        this->i = i;
    }
    int value()
    {
        return i;
    }
    ~Test()
    {
    }
};
int main()
{
    for(int i=0; i<5; i++)
    {
        Test* p = new Test(i);                               //没有归还空间
        
        cout << p->value() << endl;            
    }   
    return 0;

}

需要一个特殊的指针,生命周期结束时主动释放堆空间,

一片堆空间最多只能由一个指针标识(只需要拷贝构造函数和重载赋值操作符)

杜绝指针运算和指针比较。

解决方法:

重载指针特征操作符(->和*)

只能通过类的成员函数重载,重载函数不能使用参数,只能定义一个重载函数。

#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);                         //用pointer类对象代替指针
    
    cout << p1->value() << endl;
    
    Pointer p2 = p1;
    
    cout << p1.isNull() << endl;
    
    cout << p2->value() << endl;
    
    return 0;

}

智能指针:通过一个对象来代替指针,模拟指针的行为。

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

指针特征操作符(->和 *)可以被重载,重载指针特征符能够使用对象代替指针,最大程度的避免内存问题。

猜你喜欢

转载自blog.csdn.net/ws857707645/article/details/80239289