added iOS source code
[wl-app.git] / iOS / Pods / Realm / include / core / realm / util / shared_ptr.hpp
1 /*************************************************************************
2  *
3  * Copyright 2016 Realm Inc.
4  *
5  * Licensed under the Apache License, Version 2.0 (the "License");
6  * you may not use this file except in compliance with the License.
7  * You may obtain a copy of the License at
8  *
9  * http://www.apache.org/licenses/LICENSE-2.0
10  *
11  * Unless required by applicable law or agreed to in writing, software
12  * distributed under the License is distributed on an "AS IS" BASIS,
13  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14  * See the License for the specific language governing permissions and
15  * limitations under the License.
16  *
17  **************************************************************************/
18
19 #ifndef REALM_SHARED_PTR_HPP
20 #define REALM_SHARED_PTR_HPP
21
22 #include <cstdlib> // size_t
23
24 namespace realm {
25 namespace util {
26
27 template <class T>
28 class SharedPtr {
29 public:
30     SharedPtr(T* p)
31     {
32         init(p);
33     }
34
35     SharedPtr()
36     {
37         init(0);
38     }
39
40     ~SharedPtr()
41     {
42         decref();
43     }
44
45     SharedPtr(const SharedPtr<T>& o)
46         : m_ptr(o.m_ptr)
47         , m_count(o.m_count)
48     {
49         incref();
50     }
51
52     SharedPtr<T>& operator=(const SharedPtr<T>& o)
53     {
54         if (m_ptr == o.m_ptr)
55             return *this;
56         decref();
57         m_ptr = o.m_ptr;
58         m_count = o.m_count;
59         incref();
60         return *this;
61     }
62
63     T* operator->() const
64     {
65         return m_ptr;
66     }
67
68     T& operator*() const
69     {
70         return *m_ptr;
71     }
72
73     T* get() const
74     {
75         return m_ptr;
76     }
77
78     bool operator==(const SharedPtr<T>& o) const
79     {
80         return m_ptr == o.m_ptr;
81     }
82
83     bool operator!=(const SharedPtr<T>& o) const
84     {
85         return m_ptr != o.m_ptr;
86     }
87
88     bool operator<(const SharedPtr<T>& o) const
89     {
90         return m_ptr < o.m_ptr;
91     }
92
93     size_t ref_count() const
94     {
95         return *m_count;
96     }
97
98 private:
99     void init(T* p)
100     {
101         m_ptr = p;
102         try {
103             m_count = new size_t(1);
104         }
105         catch (...) {
106             delete p;
107             throw;
108         }
109     }
110
111     void decref()
112     {
113         if (--(*m_count) == 0) {
114             delete m_ptr;
115             delete m_count;
116         }
117     }
118
119     void incref()
120     {
121         ++(*m_count);
122     }
123
124     T* m_ptr;
125     size_t* m_count;
126 };
127 }
128 }
129
130 #endif