【数据结构】27_再论智能指针 (上)

SmartPointer 的设计方案

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

新的设计方案

【数据结构】27_再论智能指针 (上)_第1张图片

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

    • 纯虚析构函数 virtual ~Pointer() = 0
    • 重载 operator-> ()
    • 重载 operator* ()
template 
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 
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
class SmartPointer : public Pointer
{
public:
    SmartPointer(T *p = nullptr) : Pointer(p)
    {
    }

    SmartPointer(const SmartPointer &obj) : Pointer(nullptr)
    {
        this->m_pointer = obj.m_pointer;
        const_cast(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(obj).m_pointer = nullptr;

            delete pointer;
        }

        return *this;
    }

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

}

#endif // SMARTPOINTER_H

文件:main.cpp

#include 
#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 sp = new Test();
    SmartPointer 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...

【数据结构】27_再论智能指针 (上)_第2张图片

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

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

你可能感兴趣的