shared_ptr 的實現,沒有帶模版,待完善
阿新 • • 發佈:2020-11-19
1 #include<iostream> 2 #include<string> 3 #include<cassert> 4 using namespace std; 5 6 class SmartPointer { 7 public: 8 int* ptr; 9 int* count; 10 11 public: 12 13 SmartPointer(int* temp=nullptr):ptr(temp){ 14 cout << "建構函式" << endl; 15 if(ptr) { 16 count = new int(1); 17 } 18 else { 19 count = new int(0); 20 } 21 } 22 23 24 25 26 SmartPointer(const SmartPointer& src) { 27 if (this != &src) { 28 ptr = src.ptr; 29 count = src.count;30 (*count)++; 31 } 32 33 } 34 35 36 SmartPointer& operator=(const SmartPointer& src) { 37 if (ptr == src.ptr) { 38 return *this; 39 } 40 if (ptr) { 41 (*count)--; 42 if ((*count) == 0) { 43 deleteptr; 44 delete count; 45 } 46 } 47 ptr = src.ptr; 48 count = src.count; 49 (*count)++; 50 } 51 52 53 int& operator*() { 54 assert(ptr != nullptr); 55 return *ptr; 56 } 57 58 59 int* operator->() { 60 assert(ptr != nullptr); 61 return ptr; 62 } 63 64 ~SmartPointer() { 65 (*count)--; 66 if (*count == 0) { 67 delete count; 68 delete ptr; 69 } 70 } 71 72 int use_count() const { 73 return *count; 74 } 75 76 77 }; 78 79 int main() 80 { 81 SmartPointer sp(new int(10)); 82 std::cout << sp.use_count() << std::endl; 83 84 SmartPointer sp2(sp); 85 std::cout << sp.use_count() << std::endl; 86 std::cout << sp2.use_count() << std::endl; 87 88 SmartPointer sp3(new int(20)); 89 std::cout << sp3.use_count() << std::endl; 90 91 92 sp2 = sp3; 93 std::cout << sp.use_count() << std::endl; 94 std::cout << sp2.use_count() << std::endl; 95 std::cout << sp3.use_count() << std::endl; 96 //delete operator 97 }