SmartPointer
生活随笔
收集整理的這篇文章主要介紹了
SmartPointer
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
文章目錄
- 1 繼承關系類圖
- 2 代碼實現
1 繼承關系類圖
2 代碼實現
SmartPointer.h
#ifndef SMARTPOINTER_H #define SMARTPOINTER_H#include "pointer.h"namespace LemonLib { template <typename T> class SmartPointer : public Pointer<T> { public:SmartPointer(T* p = NULL) : Pointer<T>(p){}SmartPointer(const SmartPointer<T>& obj) : Pointer<T>(NULL){this->m_pointer = obj.m_pointer;const_cast<SmartPointer<T>&>(obj).m_pointer = NULL; /* 同一個對象只允許有一個智能指針指向 */}SmartPointer<T>& operator = (const SmartPointer<T>& obj){if (this != &obj) /* 防止自賦值,需要用指針進行判斷 */{T* p = this->m_pointer;this->m_pointer = obj.m_pointer;const_cast<SmartPointer<T>&>(obj).m_pointer = NULL; /* 同一個對象只允許有一個智能指針指向 */delete p; /* 最后才delete,保證異常安全 */}return *this;}~SmartPointer(){delete this->m_pointer;} }; }#endif // SMARTPOINTER_Hmain.cpp
#include <iostream> #include "Object.h" #include "Exception.h" #include "List.h" #include "Seqlist.h" #include "Staticlist.h" #include "Dynamiclist.h" #include "Staticarray.h" #include "DynamicArray.h" #include "Linklist.h" #include "Staticlinklist.h" #include "Smartpointer.h"using namespace std; using namespace LemonLib;class Test { public:Test(){cout << "Test()" << endl;}~Test(){cout << "~Test()" << endl;} };int main() {SmartPointer<Test> pointer = new Test();SmartPointer<Test> psn;psn = pointer;return 0; }總結
以上是生活随笔為你收集整理的SmartPointer的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 红星苹果需要授粉吗?
- 下一篇: ARP初始化