| OLD | NEW |
| (Empty) |
| 1 // Copyright 2016 PDFium Authors. All rights reserved. | |
| 2 // Use of this source code is governed by a BSD-style license that can be | |
| 3 // found in the LICENSE file. | |
| 4 | |
| 5 // Original code copyright 2014 Foxit Software Inc. http://www.foxitsoftware.com | |
| 6 | |
| 7 #ifndef CORE_FXCRT_INCLUDE_CFX_WEAK_PTR_H_ | |
| 8 #define CORE_FXCRT_INCLUDE_CFX_WEAK_PTR_H_ | |
| 9 | |
| 10 #include <memory> | |
| 11 | |
| 12 #include "core/fxcrt/include/cfx_retain_ptr.h" | |
| 13 #include "core/fxcrt/include/fx_system.h" | |
| 14 | |
| 15 template <class T, class D = std::default_delete<T>> | |
| 16 class CFX_WeakPtr { | |
| 17 public: | |
| 18 CFX_WeakPtr() {} | |
| 19 CFX_WeakPtr(const CFX_WeakPtr& that) : m_pHandle(that.m_pHandle) {} | |
| 20 CFX_WeakPtr(CFX_WeakPtr&& that) { Swap(that); } | |
| 21 CFX_WeakPtr(std::unique_ptr<T, D> pObj) | |
| 22 : m_pHandle(new Handle(std::move(pObj))) {} | |
| 23 | |
| 24 explicit operator bool() const { return m_pHandle && !!m_pHandle->Get(); } | |
| 25 bool HasOneRef() const { return m_pHandle && m_pHandle->HasOneRef(); } | |
| 26 T* operator->() { return m_pHandle->Get(); } | |
| 27 const T* operator->() const { return m_pHandle->Get(); } | |
| 28 CFX_WeakPtr& operator=(const CFX_WeakPtr& that) { | |
| 29 m_pHandle = that.m_pHandle; | |
| 30 return *this; | |
| 31 } | |
| 32 bool operator==(const CFX_WeakPtr& that) const { | |
| 33 return m_pHandle == that.m_pHandle; | |
| 34 } | |
| 35 bool operator!=(const CFX_WeakPtr& that) const { return !(*this == that); } | |
| 36 | |
| 37 T* Get() const { return m_pHandle ? m_pHandle->Get() : nullptr; } | |
| 38 void Clear() { | |
| 39 if (m_pHandle) { | |
| 40 m_pHandle->Clear(); | |
| 41 m_pHandle.Reset(); | |
| 42 } | |
| 43 } | |
| 44 void Reset() { m_pHandle.Reset(); } | |
| 45 void Reset(std::unique_ptr<T, D> pObj) { | |
| 46 m_pHandle.Reset(new Handle(std::move(pObj))); | |
| 47 } | |
| 48 void Swap(CFX_WeakPtr& that) { m_pHandle.Swap(that.m_pHandle); } | |
| 49 | |
| 50 private: | |
| 51 class Handle { | |
| 52 public: | |
| 53 explicit Handle(std::unique_ptr<T, D> ptr) | |
| 54 : m_nCount(0), m_pObj(std::move(ptr)) {} | |
| 55 void Reset(std::unique_ptr<T, D> ptr) { m_pObj = std::move(ptr); } | |
| 56 void Clear() { // Now you're all weak ptrs ... | |
| 57 m_pObj.reset(); // unique_ptr nulls first before invoking delete. | |
| 58 } | |
| 59 T* Get() const { return m_pObj.get(); } | |
| 60 T* Retain() { | |
| 61 ++m_nCount; | |
| 62 return m_pObj.get(); | |
| 63 } | |
| 64 void Release() { | |
| 65 if (--m_nCount == 0) | |
| 66 delete this; | |
| 67 } | |
| 68 bool HasOneRef() const { return m_nCount == 1; } | |
| 69 | |
| 70 private: | |
| 71 ~Handle() {} | |
| 72 | |
| 73 intptr_t m_nCount; | |
| 74 std::unique_ptr<T, D> m_pObj; | |
| 75 }; | |
| 76 | |
| 77 CFX_RetainPtr<Handle> m_pHandle; | |
| 78 }; | |
| 79 | |
| 80 #endif // CORE_FXCRT_INCLUDE_CFX_WEAK_PTR_H_ | |
| OLD | NEW |