forked from AndreyFILP/Practice
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSmartPtr2.cpp
More file actions
80 lines (68 loc) · 1.29 KB
/
SmartPtr2.cpp
File metadata and controls
80 lines (68 loc) · 1.29 KB
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
// Класс со стратегией владения объектом на основе подсчета ссылок на объект.
//
#include <iostream>
using namespace std;
template <class T>
class SmartPtr {
T* ptr;
size_t* pCounter;
void Attach(const SmartPtr& S)
{
pCounter = S.pCounter;
(*pCounter)++;
ptr = S.ptr;
}
void Detach()
{
if (ptr)
{
(*pCounter)--;
if ((*pCounter) == 0)
{
delete ptr;
delete pCounter;
}
ptr = 0;
pCounter = 0;
}
}
public:
explicit SmartPtr(T* p) {
ptr = p;
pCounter = new size_t();
*pCounter = 1;
}
SmartPtr(const SmartPtr& S) {
Attach(S);
}
SmartPtr& operator=(const SmartPtr& S) {
if (this == &S)
{
return *this;
}
Detach();
Attach(S);
return *this;
}
~SmartPtr() {
Detach();
}
size_t use_count() {
return *pCounter;
}
T& operator*() { return *ptr; }
T* operator->() { return ptr; }
};
int main()
{
SmartPtr<int> ptr(new int());
*ptr = 20;
SmartPtr<int> ptr2(ptr);
*ptr2 = 30;
SmartPtr<int> ptr3 = ptr;
//*ptr3 = 50;
//ptr = ptr3;
cout << *ptr << " " << *ptr2 << " " << *ptr3 << endl;
cout << ptr.use_count() << " " << ptr2.use_count() << " " << ptr3.use_count();
return 0;
}