簡單模仿一個智慧指標
阿新 • • 發佈:2019-01-22
簡單版本...代理模式和指標操作符過載的結合體...
#ifndef __AUTO_PTR_H_ #define __AUTO_PTR_H_ #include <iostream> namespace std_plus { template<class T> class auto_ptr { public: auto_ptr(T *ptr) { _ptr = ptr; refer_count = new int(0); std::cout << "refer_count:" << *refer_count <<std::endl; } auto_ptr(const auto_ptr<T> &ap_t) { this->_ptr = ap_t._ptr; this->refer_count = ap_t.refer_count; (*refer_count)+=1; std::cout << "refer_count:" << *refer_count <<std::endl; } ~auto_ptr() { if (*refer_count == 0) { std::cout << "auto_ptr auto to delete..." << std::endl; delete _ptr; delete refer_count; } _ptr = NULL; } T* operator->() { return _ptr; } T& operator*() { return *_ptr; } private: T *_ptr; int *refer_count; }; } #endif