智能指针的实现(指针运算符重载)

智能指针的实现

Person类有showAge 成员函数

如果new出来的Person对象,就要让程序员自觉的去释放  delete

有了智能指针,让智能指针托管这个Person对象,对象的释放就不用操心了,让智能指针管理

为了让智能指针想普通的Person*指针一样使用 就要重载 -> 和*

#define _CRT_SECURE_NO_WARNINGS
#include <iostream>
using namespace std;

class Person
{
public:
    Person(){}
    Person(int a)
    {
        this->m_Age = a;
    }
    void showAge()
    {
        cout << "Person的年龄是:" << this->m_Age << endl;
    }

    ~Person()
    {
        cout << "析构了Person" << endl;
    }
    int m_Age;
};

//智能指针
//用来托管自定义类型的对象,让对象进行自动的释放
class smartPointer
{
public:
    smartPointer(Person* person)
    {
        this->person = person;
    }

    //重载->让智能指针对象 像Person *p一样去使用
    Person* operator->()
    {
        return  this->person; //返回person指针
    }
    //重载* 
    Person& operator*()
    {
        return *this->person; //要返回的是person的本体 所以return * this->person
    }

    ~smartPointer()
    {
        cout << "析构了智能指针" << endl;
        if (this->person != NULL)
        {
            delete this->person;        //删除Person对象的指针
            this->person = NULL;        //防止野指针
        }
    }

    Person * person;    //维护Person指针
};

void test()
{
    //Person* p = new Person(100); //如果忘记释放,那么就会造成内存泄漏
    smartPointer sp(new Person(10));    //开辟到了栈上,调用完毕会自动释放 调用析构
    //smartPointer* sp = new smartPointer(new Person(10)); //开辟在堆区 不会自动释放
    sp->showAge();          //因为重载了->  所以sp->返回的是person的指针,正常应该是sp->->showAge() 才会调用Person的showAge方法
                            //编译器优化了 把->->减少一个箭头 即->
    (*sp).showAge();
}

int main()
{
    test();
    system("Pause");
    return 0;
}
原文地址:https://www.cnblogs.com/yifengs/p/15175134.html