-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathRefCounter.cpp
87 lines (67 loc) · 1.76 KB
/
RefCounter.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
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
/**
* \file RefCounter.cpp
* \brief How do I do simple reference counting
*
* \review
*
* https://isocpp.org/wiki/faq/freestore-mgmt#ref-count-simple
*/
#include <StdStream/StdStream.h>
#include <StdTest/StdTest.h>
#include <Stl.h>
//--------------------------------------------------------------------------------------------------
class FredPtr;
class Fred
{
public:
Fred() :
count_(0)
/*...*/
{
}
///< All ctors set count_ to "0"
// ...
private:
unsigned count_ {};
///< count_ must be initialized to 0 by all constructors
///< count_ is the number of FredPtr objects that point at this
friend class FredPtr;
};
//--------------------------------------------------------------------------------------------------
class FredPtr
{
public:
FredPtr(Fred* p) : _p(p) { ++ _p->count_; } // p must not be null
FredPtr(const FredPtr& p) : _p(p._p) { ++ _p->count_; }
~FredPtr() { if (--_p->count_ == 0) delete _p; }
/**
* DO NOT CHANGE THE ORDER OF THESE STATEMENTS!
* (This order properly handles self-assignment)
* (This order also properly handles recursion, e.g., if a Fred contains FredPtrs)
*/
FredPtr &
operator = (const FredPtr& p)
{
Fred* const old = _p;
_p = p._p;
++ _p->count_;
if (-- old->count_ == 0) {
delete old;
}
return *this;
}
Fred* operator -> () { return _p; }
Fred& operator * () { return *_p; }
private:
Fred *_p {};
///< _p is never NULL
};
//--------------------------------------------------------------------------------------------------
int main(int, char **)
{
// std::cout << STD_TRACE_VAR("") << std::endl;
return EXIT_SUCCESS;
}
//--------------------------------------------------------------------------------------------------
#if OUTPUT
#endif