11#include < string>
22
3- // Хранит счётчики
3+ // Хранит свединия об объекте
44struct ControlCount
55{
66 size_t shared_count;
@@ -18,6 +18,17 @@ class SharedPtr {
1818std::string* ptr_;
1919ControlCount* control;
2020
21+ void ResourceRelease () {
22+ if (control) {
23+ --control->shared_count ;
24+ if (!control->shared_count ) {
25+ delete ptr_;
26+ if (!control->weak_count ) {
27+ delete control;
28+ }
29+ }
30+ }
31+ }
2132public:
2233// Дефолтный конструктор
2334SharedPtr () : ptr_(nullptr ), control(nullptr ) {}
@@ -56,17 +67,51 @@ SharedPtr(SharedPtr&& other) noexcept : ptr_(other.ptr_), control(other.control)
5667}
5768
5869// Оператор присвоения при копировании
59- SharedPtr& operator =(const SharedPtr& other) {
70+ SharedPtr& operator =(const SharedPtr& other);
71+
72+ // Оператор присвоения при перемещении
73+ SharedPtr& operator =(SharedPtr&& other) noexcept ;
74+
75+ // Оператор bool, *, ->
76+ explicit operator bool () const { return ptr_ != nullptr ; }
77+
78+ std::string& operator *() const { return *ptr_; }
79+
80+ std::string* operator ->() const { return ptr_; }
81+
82+ // Методы
83+ std::string* Get () const { return ptr_; }
84+
85+ void Reset (std::string* p);
86+
87+ void Swap (SharedPtr& other);
88+
89+ size_t UseCount () const ;
90+ };
91+
92+
93+
94+ // Реализация методов
95+ void SharedPtr::Reset (std::string* p) {
96+ ResourceRelease ();
97+
98+ ptr_ = p;
99+ (ptr_) ? control = new ControlCount (p) : control = nullptr ;
100+ }
101+
102+ void SharedPtr::Swap (SharedPtr& other) {
103+ std::swap (ptr_, other.ptr_ );
104+ std::swap (control, other.control );
105+ }
106+
107+ size_t SharedPtr::UseCount () const {
108+ return (control) ? control->shared_count : 0 ;
109+ }
110+
111+ // Реализация операторов
112+ SharedPtr& SharedPtr::operator =(const SharedPtr& other) {
60113 if (this != &other) {
61- if (control) {
62- --control->shared_count ;
63- if (!control->shared_count ) {
64- delete ptr_;
65- if (!control->weak_count ) {
66- delete control;
67- }
68- }
69- }
114+ ResourceRelease ();
70115
71116 ptr_ = other.ptr_ ;
72117 control = other.control ;
@@ -77,18 +122,9 @@ SharedPtr& operator=(const SharedPtr& other) {
77122 return *this ;
78123}
79124
80- // Оператор присвоения при перемещении
81- SharedPtr& operator =(SharedPtr&& other) noexcept {
125+ SharedPtr& SharedPtr::operator =(SharedPtr&& other) noexcept {
82126 if (this != &other) {
83- if (control) {
84- --control->shared_count ;
85- if (!control->shared_count ) {
86- delete ptr_;
87- if (!control->weak_count ) {
88- delete control;
89- }
90- }
91- }
127+ ResourceRelease ();
92128
93129 ptr_ = other.ptr_ ;
94130 control = other.control ;
@@ -99,7 +135,7 @@ SharedPtr& operator=(SharedPtr&& other) noexcept {
99135}
100136
101137
102- };
138+
103139
104140
105141
0 commit comments