1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147
| #include <bits/stdc++.h> #include <type_traits> using namespace std;
class Point { public: int a; int b; int c;
public: Point() = default; Point(int _a, int _b, int _c) : a(_a), b(_b), c(_c) {} };
template <typename _Tp> class _Ref_count { private: _Tp *_M_ptr; int _M_use_count; int _M_weak_count;
public: _Ref_count(_Tp *_Px) { _M_ptr = _Px; _M_use_count = 1; _M_weak_count = 1; }
void _Decref() { _M_use_count--; _M_weak_count--; if (_M_weak_count == 0) { delete _M_ptr; delete this; } }
void _Incref() { _M_use_count++; _M_weak_count++; }
int _Get_uses() const { return _M_use_count; } };
template <typename _Tp> class shared_pointer { private: _Ref_count<_Tp> *_M_refcount; _Tp *_M_ptr;
public: shared_pointer(_Tp *_Px) { _M_ptr = _Px; _M_refcount = new _Ref_count(_Px); }
shared_pointer(shared_pointer<_Tp> &_Sp) { _M_refcount = _Sp._M_refcount; _M_ptr = _Sp._M_ptr; _M_refcount->_Incref(); }
~shared_pointer() { _M_refcount->_Decref(); }
_Tp *get() { return _M_ptr; }
int use_count() { return _M_refcount->_Get_uses(); }
void reset(_Tp *_Px) { shared_pointer<_Tp>(_Px).swap(*this); }
void reset() { _M_refcount->_Decref(); _M_refcount = nullptr; _M_ptr = nullptr; }
void swap(shared_pointer &_Right) { std::swap(_M_ptr, _Right._M_ptr); std::swap(_M_refcount, _Right._M_refcount); }
explicit operator bool() const { return use_count() != 0; }
_Tp operator*() const noexcept { return *_M_ptr; }
_Tp *operator->() const noexcept { return _M_ptr; } };
int main() { shared_pointer<Point> sp1(new Point(1, 2, 3)); cout << "访问元素:\n"; cout << sp1->a << sp1->b << "\n"; cout << "获取引用计数:\n"; cout << sp1.use_count() << "\n";
shared_pointer<Point> sp2 = sp1; auto sp3(sp1); cout << "构造sp2和sp3后的引用计数:\n"; cout << sp1.use_count() << "\n"; cout << sp2.use_count() << "\n"; cout << sp3.use_count() << "\n"; cout << "reset sp3后:\n"; sp3.reset(new Point(3, 2, 1)); cout << sp1.use_count() << "\n"; cout << sp2.use_count() << "\n"; cout << sp3.use_count() << "\n"; cout << sp3->a << sp3->b << "\n"; return 0; }
|