| 1 |
// SPDX-License-Identifier: GPL-3.0-or-later |
| 2 |
#pragma once |
| 3 |
|
| 4 |
#include <CoreFoundation/CoreFoundation.h> |
| 5 |
|
| 6 |
/** |
| 7 |
* RAII wrapper for Core Foundation references (CFRetain/CFRelease). |
| 8 |
* |
| 9 |
* Automatically releases the held reference on destruction. Eliminates |
| 10 |
* the class of bugs where an early return or exception skips a CFRelease. |
| 11 |
* |
| 12 |
* By default the constructor **adopts** (takes ownership of) a +1 reference |
| 13 |
* returned by CF *Create* / *Copy* functions — no extra retain. |
| 14 |
* |
| 15 |
* \code |
| 16 |
* // Adopt a +1 ref from a Create/Copy function (no extra retain): |
| 17 |
* CFRef<CGEventRef> event = CGEventCreateKeyboardEvent(src, key, YES); |
| 18 |
* |
| 19 |
* // Adopt a +1 ref from a Copy function: |
| 20 |
* CFRef<CFArrayRef> items = LSSharedFileListCopySnapshot(list, &seed); |
| 21 |
* |
| 22 |
* // Implicit conversion to the raw type for passing to CF APIs: |
| 23 |
* CGEventPost(kCGHIDEventTap, event); |
| 24 |
* |
| 25 |
* // Release is automatic; no manual CFRelease needed. |
| 26 |
* \endcode |
| 27 |
*/ |
| 28 |
template <typename T> |
| 29 |
class CFRef { |
| 30 |
public: |
| 31 |
CFRef() : m_ref(nullptr) {} |
| 32 |
|
| 33 |
// Adopts a +1 reference (from Create/Copy). Intentionally implicit so |
| 34 |
// `CFRef<X> x = SomeCreate(...)` works naturally. |
| 35 |
// NOLINTNEXTLINE(google-explicit-constructor) |
| 36 |
CFRef(T ref) : m_ref(ref) {} |
| 37 |
|
| 38 |
~CFRef() |
| 39 |
{ |
| 40 |
if (m_ref) |
| 41 |
CFRelease(m_ref); |
| 42 |
} |
| 43 |
|
| 44 |
CFRef(const CFRef &other) : m_ref(other.m_ref) |
| 45 |
{ |
| 46 |
if (m_ref) |
| 47 |
CFRetain(m_ref); |
| 48 |
} |
| 49 |
|
| 50 |
CFRef &operator=(const CFRef &other) |
| 51 |
{ |
| 52 |
if (m_ref != other.m_ref) { |
| 53 |
if (m_ref) |
| 54 |
CFRelease(m_ref); |
| 55 |
m_ref = other.m_ref; |
| 56 |
if (m_ref) |
| 57 |
CFRetain(m_ref); |
| 58 |
} |
| 59 |
return *this; |
| 60 |
} |
| 61 |
|
| 62 |
CFRef &operator=(T ref) |
| 63 |
{ |
| 64 |
if (m_ref != ref) { |
| 65 |
if (m_ref) |
| 66 |
CFRelease(m_ref); |
| 67 |
m_ref = ref; |
| 68 |
} |
| 69 |
return *this; |
| 70 |
} |
| 71 |
|
| 72 |
T get() const { return m_ref; } |
| 73 |
operator T() const { return m_ref; } |
| 74 |
explicit operator bool() const { return m_ref != nullptr; } |
| 75 |
|
| 76 |
private: |
| 77 |
T m_ref; |
| 78 |
}; |