-
Notifications
You must be signed in to change notification settings - Fork 0
/
raw_smart.cpp
71 lines (52 loc) · 1.09 KB
/
raw_smart.cpp
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
#include <stdio.h>
#include <iostream>
#include <memory>
using namespace std;
class C {
public:
C() : n(0) {};
~C(){cout << "~destructor" << endl;}
int n;
};
void double_free_error(){
C* a = new C();
C* b = new C();
a->n = 1;
b = a;
cout << a->n << endl;
cout << a << endl;
cout << b << endl;
delete a;
delete b;
}
void smart_pointer(){
shared_ptr<C> a = make_shared<C>();
shared_ptr<C> b = make_shared<C>();
weak_ptr<C> w; //weak reference
a->n = 1;
//change ownership
b = a;
// copy ref
// w = a;
// Has to be copied into a shared_ptr before usage
auto sp = w.lock();
auto sp_cpy = w.lock();
cout << a->n << endl;
cout << b->n << endl;
if(sp)
cout << sp->n << endl;
if(sp_cpy)
cout << sp_cpy->n << endl;
cout << a << endl;
cout << b << endl;
if(sp)
cout << sp << endl;
if(sp_cpy)
cout << sp_cpy << endl;
}
int main()
{
smart_pointer();
// double_free_error();
return 0;
}