언어/C++

[C++] shared_ptr 직접 구현해보기

겜도리도리 2021. 12. 16. 00:58
반응형

C++로 shared_ptr 직접 구현해보기

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
#include<iostream>
using namespace std;
 
template <typename T>
class My_shared_ptr {
private:
    T* value;
    int* cnt;
public:
    My_shared_ptr() {
 
    }
    My_shared_ptr(T* value) {
        this->value = value;
        cnt = new int (1);
    }
    My_shared_ptr(const My_shared_ptr& other) {
        value = other.value;
        cnt = other.cnt;
        (*cnt)++;
    }
    My_shared_ptr& operator=(const My_shared_ptr& other) {
        value = other.value;
        cnt = other.cnt;
        (*cnt)++;
        return *this;
    }
    void reset() {
        if (--(*cnt) == 0) {
            delete value;
            delete cnt;
        }
        else {
            value = nullptr;
            cnt = nullptr;
        }
    }
    int use_count() {
        return *cnt;
    }
};
int main()
{
    My_shared_ptr<int> sp1(new int(5));
    cout << sp1.use_count() << endl// 1
    My_shared_ptr<int> sp2(sp1);
    cout << sp2.use_count() << endl// 2
    My_shared_ptr<int> sp3 = sp2;
    cout << sp3.use_count() << endl// 3
    sp3.reset();
    cout << sp2.use_count() << endl// 2
    cout << sp1.use_count() << endl// 2
    return 0;
}
cs
반응형