智慧指標shared_ptr的實現
阿新 • • 發佈:2018-11-14
#include <iostream> using namespace std; template <class T> class smart { public: smart() = default; smart(T* ptr = nullptr):_ptr(ptr) { if (_ptr) { _count = new size_t(1); } else { _count = new size_t(0); } } //copy constructorsmart(const smart &ptr) { if (this != &ptr) { this->_ptr = ptr._ptr; this->_count = ptr._count; (*this->_count)++; } } //operator = smart operator = (const smart &ptr) { if (this->_ptr == ptr->_ptr) {return *this; } //原share_ptr引用次數減一 if(this->_ptr) { *(this->_count)--; if (this->_count == 0) { delete this->_ptr; delete this->_count; } } this->_ptr = ptr._ptr; this->_count = ptr._count;*(this->_count)++; return *this; } //operator * T& operator * () { if (this->_ptr) return *(this->_ptr); } //operator -> T& operator -> () { if (this->_ptr) return *(this->_ptr); } ~smart() { *(this->_count)--; if (*this->_count == 0) { delete this->_ptr; delete this->_count; } } //return reference counting size_t use_count() { return *this->_count; } //return ptr T objectInPtr() { return *this->_ptr; } T* use_ptr() { return this->_ptr; } private: T* _ptr; size_t* _count; }; int main() { int a = 5; int *b = &a; smart<int> c(b); cout << c.use_count() << endl; smart<int> d = c; cout << sizeof(smart<int>) << "B" << endl; cout << c.use_count() << endl; cout << d.use_count() << endl; cout << "C:" << &c << " D:" << &d << endl; cout << c.use_ptr() << ":" << d.use_ptr() << endl; cout << c.objectInPtr() << ":" << d.objectInPtr() << endl; system("pause"); return 0; }