- 指針生命週期結束時主動釋放堆空間
- 一片堆空間最多隻能由一個指針標識
- 杜絕指針運算和指針比較
Poniter 是智能指針的抽象父類(模板)ios
- 純虛析構函數 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.cppthis
#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; }
輸出:spa
Test() 10 10 1 0 ~Test()
思考
如何實現 SharedPointer 使得多個智能指針對象能夠指向同一片堆空間,同時支持內存的自動釋放?
以上內容整理於狄泰軟件學院系列課程,請你們保護原創!設計