-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathshared_ptr.cpp
More file actions
72 lines (60 loc) · 1.4 KB
/
shared_ptr.cpp
File metadata and controls
72 lines (60 loc) · 1.4 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
#include <iostream>
#include <atomic>
template <typename T>
class MySharedPtr{
public:
MySharedPtr(T val){
resource_ptr = new T(val);
c_ptr = new int(1);
};
MySharedPtr<T>(const MySharedPtr<T> & ptr){
std::cout << "copy constructor \n";
resource_ptr = ptr.resource_ptr;
(*ptr.c_ptr)++;
this->c_ptr = ptr.c_ptr;
}
MySharedPtr<T>& operator=(const MySharedPtr<T> & ptr){
std::cout << "copy assignment operator\n";
if(this != &ptr){
(*ptr.c_ptr)++;
this->c_ptr = ptr.c_ptr;
this->resource_ptr = ptr.resource_ptr;
}
return *this;
}
MySharedPtr(MySharedPtr && ptr) = delete;
MySharedPtr & operator=(MySharedPtr && ptr) = delete;
MySharedPtr & operator *(){
return resource_ptr;
}
MySharedPtr* operator ->(){
return resource_ptr;
}
virtual ~MySharedPtr(){
std::cout << *c_ptr << '\n';
if(*c_ptr > 0){
(*c_ptr)--;
}else{
delete c_ptr;
delete resource_ptr;
}
}
int use_count(){
return *c_ptr;
}
private:
int * c_ptr;
T * resource_ptr;
};
int main(){
int x;
MySharedPtr<decltype(x)> sp(1);
{
MySharedPtr<decltype(x)> sp1(2);
sp1 = sp;
std::cout << "use count is " << sp.use_count() << '\n';
}
sp = sp;
std::cout << "use count is " << sp.use_count() << '\n';
return 0;
}