SmartPtr
Posted masteryan576356467
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了SmartPtr相关的知识,希望对你有一定的参考价值。
// smart pointer implements #include <iostream> #include <memory> using namespace std; template<typename T> class SharePtr; template<typename T> class ResPtr { // manage res of memory private: T* res_p; // point res int use_num; // count ResPtr(T *p) : res_p(p), use_num(1){ cout << "the constructor of ResPtr "; } ~ResPtr(){ delete res_p; cout << "the destructor of ResPtr "; } friend class SharePtr<T>; }; template<typename T> class SharePtr { public: SharePtr(T *p, T i) : ptr(new ResPtr<T>(p)), val(i){ cout << "the constructor of SharePtr and the use count is " << ptr->use_num << endl;; } SharePtr(const SharePtr& rhs) : ptr(rhs.ptr), val(rhs.val) { ++ptr->use_num; cout << "the copy constructor of SharePtr and the use of count is " << ptr->use_num << endl; } ~SharePtr() { cout << "the destructor of SharePtr and the use of count is " << ptr->use_num << endl; if(--ptr->use_num == 0){ cout << "relese memory "; delete ptr; } } T &operator*(){ return *this->ptr->res_p; } T *operator->(){ return this->ptr->res_p; } private: ResPtr<T> *ptr; // point use_count T val; }; // test code int main() { { SharePtr<int> hpa = SharePtr<int>{ new int (42), 100 }; { // copy three objects SharePtr<int> hpb{hpa}; SharePtr<int> hpc{hpb}; SharePtr<int> hpd{hpc}; }; cout << "inner end "; } cout << "middle end "; return 0; }
以上是关于SmartPtr的主要内容,如果未能解决你的问题,请参考以下文章