-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path26_smart_pointer1.cpp
More file actions
64 lines (52 loc) ยท 1.64 KB
/
26_smart_pointer1.cpp
File metadata and controls
64 lines (52 loc) ยท 1.64 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
#include <iostream>
// ์ค๋งํธ ํฌ์ธํฐ
// ๊ฐ๋
: ์์ ๊ฐ์ฒด๊ฐ ๋ค๋ฅธ ํ์
์ ํฌ์ธํฐ ์ญํ ์ ํ๋ ๊ฒ
// ์๋ฆฌ:
// ์ฅ์ : primitive pointer๊ฐ ์๋ ๊ฐ์ฒด์ด๊ธฐ ๋๋ฌธ์ ์์ฑ/๋ณต์ฌ/๋์
/์๋ฉธ ๋ฑ์ ์๊ฐ์ ๋ํ ์์ฉ์ ํ ์ ์๋ค.
// ๋ํ์ ์ผ๋ก ์๋ฉธ์์์ ํ ๋น๋ ๊ฐ์ฒด๋ฅผ ํจ๊ป ์ ๋ฆฌํ ์ ์๋ค.
class Car
{
public:
void Go() { std::cout << "Go" << std::endl; }
~Car() { std::cout << "~Car" << std::endl; }
};
template <typename T>
class Ptr
{
T *obj;
int *ref;
public:
Ptr(T *p = 0) : obj(p)
{
ref = new int;
*ref = 1;
}
Ptr(const Ptr<T> &p) : obj(p.ref), ref(p.ref)
{
++(*ref);
}
~Ptr()
{
if (nullptr != ref && 0 == --(*ref))
{
delete obj;
delete ref;
}
}
T *operator->() { return obj; }
T &operator*() { return *obj; }
};
int main()
{
// Ptr์ ๋ฉค๋ฒ๋ณ์๋ก Car์ ํฌ์ธํฐ๊ฐ ์๊ธด ํ๋, ๊ฐ์ฒด ์์ฒด๋ฅผ Car์ ํฌ์ธํฐ์ฒ๋ผ ์ฌ์ฉ: ์ค๋งํธ ํฌ์ธํฐ
Ptr<Car> p = new Car; // Ptr p(new Car);
p->Go(); // p.operator->()Go() => (p.operator->())->Go()
std::cout << sizeof(p) << std::endl;
std::cout << sizeof(Car *) << std::endl;
// Ptr p๊ฐ local object์ด๊ธฐ ๋๋ฌธ์ ํจ์ ์ข
๋ฃ์ ์๋ฉธ๋๋ค. ์ด ๋, ํ ๋น๋ ๊ฐ์ฒด Car์ ์๋ฉธ์๋ง ํธ์ถํด์ฃผ๋ฉด, ์์ ํ๊ฒ ๋ฉ๋ชจ๋ฆฌ ์ฌ์ฉ์ ํ ์ ์๋ค.
(*p).Go();
// ์ค๋งํธ ํฌ์ธํฐ๋ ๋ฐ๋์ "์์ ๋ณต์ฌ" ๋ฌธ์ ๋ฅผ ํด๊ฒฐํด์ผ ํฉ๋๋ค.
// ์ฐธ์กฐ ๊ณ์ Reference count ๋ฅผ ์ฌ์ฉํด์ ํด๊ฒฐํ๋ค.
Ptr<int> p1 = new int;
Ptr<int> p2 = p1;
}