智慧指標的實現
阿新 • • 發佈:2018-12-17
1 智慧指標
智慧實現需要實現的功能:
- 指標生命週期結束後主動釋放堆空間
- 一片堆空間最多隻能由一個指標標識
- 杜絕指標運算和指標比較(不過載相關的操作符即可)
2 程式碼實現
實現檔案:SmartPointer.h
#ifndef SMARTPOINTER_H
#define SMARTPOINTER_H
namespace LemonLib
{
template <typename T>
class SmartPointer
{
protected:
T* m_pointer;
public:
SmartPointer(T* p = NULL)
{
m_pointer = p;
}
SmartPointer(const SmartPointer<T>& obj)
{
m_pointer = obj.m_pointer;
const_cast<SmartPointer<T>&>(obj).m_pointer = NULL; /* 同一個物件只允許有一個智慧指標指向 */
}
SmartPointer<T>& operator = (const SmartPointer<T> & obj)
{
if (this != &obj) /* 防止自賦值,需要用指標進行判斷 */
{
delete m_pointer;
m_pointer = obj.m_pointer;
const_cast<SmartPointer<T>&>(obj).m_pointer = NULL; /* 同一個物件只允許有一個智慧指標指向 */
}
return *this;
}
T* operator -> ()
{
return m_pointer;
}
T& operator * ()
{
return *m_pointer;
}
bool isNull()
{
return (m_pointer == NULL);
}
~SmartPointer()
{
delete m_pointer;
}
};
}
#endif // SMARTPOINTER_H
測試檔案:main.cpp
#include <iostream>
#include "SmartPointer.h"
using namespace std;
using namespace LemonLib;
class Test
{
private:
int m_value;
public:
Test(int value = 0)
{
m_value = value;
cout << "Test()" << endl;
}
int getValue()
{
return m_value;
}
~Test()
{
cout << "~Test()" << endl;
}
};
int main()
{
SmartPointer<Test> sp = new Test(88);
SmartPointer<Test> nsp;
nsp = sp;
cout << "nsp.value = " << nsp->getValue() << endl;
cout << "sp is Null : " << sp.isNull() << endl;
cout << "nsp is Null : " << nsp.isNull() << endl;
return 0;
}
輸出結果:
Test() nsp.value = 88 sp is Null : 1 nsp is Null : 0 ~Test()
智慧指標使用軍規:智慧指標只能用來指向堆空間中的單個物件或變數。
3 細節分析
nsp->getValue()
為什麼是對的?
這是C++標準規定的,對於ptr->mem根據ptr的型別不同,操作符->的解釋也不同:
- 當ptr的型別是內建指標型別時,等價於(*ptr).mem。
- 當ptr的型別是類時,等價於ptr.operator -> () -> men。