1 | // Copyright (C) 2016 The Qt Company Ltd. |
---|---|
2 | // SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only |
3 | #ifndef PASSREFPTR_H |
4 | #define PASSREFPTR_H |
5 | |
6 | template <typename T> class RefPtr; |
7 | |
8 | template <typename T> |
9 | class PassRefPtr { |
10 | public: |
11 | PassRefPtr() : m_ptr(0) {} |
12 | |
13 | PassRefPtr(T* ptr) |
14 | : m_ptr(ptr) |
15 | { |
16 | if (m_ptr) |
17 | m_ptr->ref(); |
18 | } |
19 | |
20 | PassRefPtr(const PassRefPtr<T>& other) |
21 | : m_ptr(other.leakRef()) |
22 | { |
23 | } |
24 | |
25 | PassRefPtr(const RefPtr<T>& other) |
26 | : m_ptr(other.get()) |
27 | { |
28 | if (m_ptr) |
29 | m_ptr->ref(); |
30 | } |
31 | |
32 | ~PassRefPtr() |
33 | { |
34 | if (m_ptr) |
35 | m_ptr->deref(); |
36 | } |
37 | |
38 | T* operator->() const { return m_ptr; } |
39 | |
40 | T* leakRef() const |
41 | { |
42 | T* result = m_ptr; |
43 | m_ptr = 0; |
44 | return result; |
45 | } |
46 | |
47 | private: |
48 | PassRefPtr<T>& operator=(const PassRefPtr<T>& t); |
49 | |
50 | protected: |
51 | mutable T* m_ptr; |
52 | }; |
53 | |
54 | template <typename T> |
55 | class Ref : public PassRefPtr<T> |
56 | { |
57 | using PassRefPtr<T>::PassRefPtr; |
58 | |
59 | template <typename PtrType> friend Ref<PtrType> adoptRef(PtrType*); |
60 | }; |
61 | |
62 | template <typename T> |
63 | Ref<T> adoptRef(T* ptr) |
64 | { |
65 | Ref<T> result; |
66 | result.m_ptr = ptr; |
67 | return result; |
68 | } |
69 | |
70 | #endif // PASSREFPTR_H |
71 |