forked from cirosantilli/cpp-cheat
-
Notifications
You must be signed in to change notification settings - Fork 0
/
shared_ptr.cpp
51 lines (41 loc) · 1.46 KB
/
shared_ptr.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
/*
# shared_ptr
Introuced in C++11, before that as part of boost.
Reference counts usages, deletes data when the last one is gone.
*/
#include "common.hpp"
int main() {
#if __cplusplus >= 201103L
{
callStack.clear();
// First reference
std::shared_ptr<NoBaseNoMember> sp1(new NoBaseNoMember(1));
assert(sp1.use_count() == 1);
assert(sp1->i == 1);
// Create reference with copy constructor.
std::shared_ptr<NoBaseNoMember> sp2(sp1);
assert(sp1.use_count() == 2);
assert(sp2->i == 1);
// Create reference with assignment constructor.
std::shared_ptr<NoBaseNoMember> sp3;
sp3 = sp1;
assert(sp1.use_count() == 3);
assert(sp3->i == 1);
// ERROR No converstion operator to pointer defined.
//NoBaseNoMember *spp = sp1;
// Replace one reference with a new pointer.
sp1 = std::shared_ptr<NoBaseNoMember>(new NoBaseNoMember(2));
// ERROR No constructor directly from pointers.
//sp1 = new NoBaseNoMember(2);
assert(sp1.use_count() == 1);
assert(sp2.use_count() == 2);
assert(sp1->i == 2);
assert(sp2->i == 1);
// Replace the remaining references and check that the destructor got called.
sp2 = sp1;
assert(callStack.back() != "NoBaseNoMember::~NoBaseNoMember()");
sp3 = sp1;
assert(callStack.back() == "NoBaseNoMember::~NoBaseNoMember()");
}
#endif
}