2 * Copyright (C) 2011 The Android Open Source Project
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
8 * http://www.apache.org/licenses/LICENSE-2.0
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
19 #include <cutils/threads.h>
20 #include <cutils/atomic.h>
22 template <class T, bool threadSafe = false>
26 explicit SmartPtr(T* ptr = (T*)NULL) {
35 m_pRefCount = new int32_t(1);
40 SmartPtr<T,threadSafe>(const SmartPtr<T,false>& rhs) {
47 m_pRefCount = rhs.m_pRefCount;
52 SmartPtr<T,threadSafe>(SmartPtr<T,true>& rhs) {
59 if (rhs.m_lock) mutex_lock(rhs.m_lock);
60 m_pRefCount = rhs.m_pRefCount;
63 if (rhs.m_lock) mutex_unlock(rhs.m_lock);
67 if (m_lock) mutex_lock(m_lock);
72 mutex_destroy(m_lock);
81 const T* constPtr() const
86 T* operator->() const {
90 T& operator*() const {
94 operator void*() const {
98 // This gives STL lists something to compare.
99 bool operator <(const SmartPtr<T>& t1) const {
100 return m_ptr < t1.m_ptr;
103 SmartPtr<T,threadSafe>& operator=(const SmartPtr<T,false>& rhs)
105 if (m_ptr == rhs.m_ptr)
108 if (m_lock) mutex_lock(m_lock);
110 m_pRefCount = rhs.m_pRefCount;
113 if (m_lock) mutex_unlock(m_lock);
118 SmartPtr<T,threadSafe>& operator=(SmartPtr<T,true>& rhs)
120 if (m_ptr == rhs.m_ptr)
123 if (m_lock) mutex_lock(m_lock);
125 if (rhs.m_lock) mutex_lock(rhs.m_lock);
126 m_pRefCount = rhs.m_pRefCount;
129 if (rhs.m_lock) mutex_unlock(rhs.m_lock);
130 if (m_lock) mutex_unlock(m_lock);
136 int32_t *m_pRefCount;
140 // Increment the reference count on this pointer by 1.
142 if (!m_pRefCount) return 0;
143 return android_atomic_inc(m_pRefCount) + 1;
146 // Decrement the reference count on the pointer by 1.
147 // If the reference count goes to (or below) 0, the pointer is deleted.
149 if (!m_pRefCount) return 0;
151 int iVal = android_atomic_dec(m_pRefCount);
167 #endif // of __SMART_PTR_H