-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathCopyOnWrite.cpp
97 lines (78 loc) · 1.69 KB
/
CopyOnWrite.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
88
89
90
91
92
93
94
95
96
97
/**
* \file CopyOnWrite.cpp
* \brief Achieve lazy copy optimization. Like lazy initialization, do the work just when you need
* because of efficiency
*
* \see https://shaharmike.com/cpp/std-string/
*
* To implement copy-on-write, a smart pointer to the real content is used to encapsulate
* the object's value, and on each modification an object reference count is checked;
* if the object is referenced more than once, a copy of the content is created before modification
*
* \review
*/
#include <StdStream/StdStream.h>
#include <StdTest/StdTest.h>
#include <Stl.h>
//--------------------------------------------------------------------------------------------------
template <class T>
class CowPtr
{
public:
using ref_ptr_t = std::shared_ptr<T>;
CowPtr(T *t) :
_sp(t)
{
}
CowPtr(const ref_ptr_t &refptr) :
_sp(refptr)
{
}
const T &
operator * () const
{
return *_sp;
}
T &
operator * ()
{
_detach();
return *_sp;
}
const T *
operator -> () const
{
return _sp.operator->();
}
T *
operator -> ()
{
_detach();
return _sp.operator->();
}
private:
ref_ptr_t _sp;
void _detach()
{
T *tmp = _sp.get();
if ( !( tmp == 0 || _sp.unique() ) ) {
_sp = ref_ptr_t( new T( *tmp ) );
}
}
};
//--------------------------------------------------------------------------------------------------
int main(int, char **)
{
#if 0
CowPtr<String> s1 = "Hello";
// Non-const detachment does nothing here
char &c = s1->operator[](4);
// Lazy-copy, shared state
CowPtr<String> s2(s1);
c = '!'; // Uh-oh
#endif
return EXIT_SUCCESS;
}
//--------------------------------------------------------------------------------------------------
#if OUTPUT
#endif