SmartPointer 的设计方案

  • 指针生命周期结束时主动释放堆空间
  • 一片堆空间最多只能由一个指针标识
  • 杜绝指针运算和指针比较

新的设计方案

image.png

  • Poniter 是智能指针的抽象父类(模板)

    • 纯虚析构函数 virtual ~Pointer() = 0
    • 重载 operator-> ()
    • 重载 operator* ()
template <typename T>
class Pointer : public Object
{
public:
    Pointer(T *p = NULL);
    T *operator->();
    T &operator*();
    bool isNull();
    T *get();
    
protected:
    T *m_pointer;
};

编程实验:智能指针的新方案

文件:Pointer.h

#ifndef POINTER_H
#define POINTER_H

#include "Object.h"

namespace DTLib
{

template <typename T>
class Pointer : public Object
{
public:
    Pointer(T *p = nullptr) : m_pointer(p)
    {
    }

    T *operator-> ()
    {
        return m_pointer;
    }

    const T *operator-> () const
    {
        return m_pointer;
    }

    T &operator* ()
    {
        return *m_pointer;
    }

    const T &operator* () const
    {
        return *m_pointer;
    }

    bool isNull() const
    {
        return (m_pointer == nullptr);
    }

    T *get() const
    {
        return m_pointer;
    }

protected:
    T *m_pointer = nullptr;
};

}

#endif // POINTER_H

[重构] 文件: SmartPointer.h

#ifndef SMARTPOINTER_H
#define SMARTPOINTER_H

#include "Pointer.h"

namespace DTLib
{

template<typename T>
class SmartPointer : public Pointer<T>
{
public:
    SmartPointer(T *p = nullptr) : Pointer<T>(p)
    {
    }

    SmartPointer(const SmartPointer &obj) : Pointer<T>(nullptr)
    {
        this->m_pointer = obj.m_pointer;
        const_cast<SmartPointer&>(obj).m_pointer = nullptr;
    }

    SmartPointer &operator= (const SmartPointer &obj)
    {
        if (this != &obj)
        {
            T *pointer = this->m_pointer;

            this->m_pointer = obj.m_pointer;
            const_cast<SmartPointer&>(obj).m_pointer = nullptr;

            delete pointer;
        }

        return *this;
    }

    ~SmartPointer()
    {
        delete this->m_pointer;
    }
};

}

#endif // SMARTPOINTER_H

文件:main.cpp

#include <iostream>
#include "SmartPointer.h"

using namespace std;
using namespace DTLib;

class Test
{
public:
    int i = 10;

    Test()
    {
        cout << "Test()" << endl;
    }

    ~Test()
    {
        cout << "~Test()" << endl;
    }

};

int main()
{
    SmartPointer<Test> sp = new Test();
    SmartPointer<Test> spn;

    cout << sp->i << endl;

    spn = sp;

    cout << spn->i << endl;

    cout << sp.isNull() << endl;
    cout << spn.isNull() << endl;

    return 0;
}

输出:

Test()
10
10
1
0
~Test()

To be continued...

image.png

思考
如何实现 SharedPointer 使得多个智能指针对象可以指向同一片堆空间,同时支持内存的自动释放?

以上内容整理于狄泰软件学院系列课程,请大家保护原创!


TianSong
734 声望138 粉丝

阿里山神木的种子在3000年前已经埋下,今天不过是看到当年注定的结果,为了未来的自己,今天就埋下一颗好种子吧