共享指针的简单实现
共享指针的简单实现,主要参考 https://www.cnblogs.com/xiehongfeng100/p/4645555.html
// Study.cpp: 定义控制台应用程序的入口点。 // #include "stdafx.h" #include <iostream> #include <vector> #include <unordered_map> #include <unordered_set> #include <queue> #include <string> #include <algorithm> #include <sstream> using namespace std; template<class T> class SmartPtr { public: SmartPtr(T *p); ~SmartPtr(); SmartPtr(const SmartPtr<T> &orig); // 浅拷贝 SmartPtr<T>& operator=(const SmartPtr<T> &rhs); // 浅拷贝 void getcount() { cout << *use_count << " "; } private: T * ptr; // 将use_count声明成指针是为了方便对其的递增或递减操作 int *use_count; }; template<class T> SmartPtr<T>::SmartPtr(T *p):ptr(p) { use_count = new int(1); if (use_count == nullptr) { p = nullptr; cout << " Allocation Error " << endl; return; } } template<class T> SmartPtr<T>::~SmartPtr() { if (--(*use_count) == 0) { delete ptr; ptr = nullptr; delete use_count; use_count = nullptr; } } template<class T> SmartPtr<T>::SmartPtr(const SmartPtr<T> &orig) { ptr = orig.ptr; use_count = orig.use_count; ++(*use_count); } template<class T> SmartPtr<T>& SmartPtr<T>::operator=(const SmartPtr<T> &rhs) { if (this == &rhs) return *this; this->~SmartPtr(); use_count = rhs.use_count; ++(*use_count); ptr = rhs.ptr; }; int main() { string* p1 = new string("hello"); SmartPtr<string> sp1(p1); string* p2 = new string("hello"); SmartPtr<string> sp2(p2); vector<SmartPtr<string>> vp; vp.push_back(sp1); vp.push_back(sp2); vp.push_back(sp2); vp.push_back(sp1); cout << "sp1 sp2 : "; sp1.getcount(); sp2.getcount(); cout << endl; vp.pop_back(); vp.pop_back(); cout << "sp1 sp2 : "; sp1.getcount(); sp2.getcount(); cout << endl; SmartPtr<string> sp3(sp1); cout << "sp1 sp2 : "; sp1.getcount(); sp2.getcount(); cout << endl; sp2 = sp2; cout << "sp1 sp2 : "; sp1.getcount(); sp2.getcount(); cout << endl; sp3 = sp2; cout << "sp1 sp2 : "; sp1.getcount(); sp2.getcount(); cout << endl; //while (1) //{ // cin >> a >> b; // cout << ((a & b) + ((a ^ b) >> 1)) << endl; //} system("pause"); return 0; }