Debian Codegraph @

src/platform/mac/objcstrong.h

raw
1 // SPDX-License-Identifier: GPL-3.0-or-later
2 #pragma once
3
4 #ifdef __OBJC__
5 # import <Foundation/NSObject.h>
6 #endif
7
8 /**
9 * RAII strong-reference holder for Objective-C objects (manual retain/release).
10 *
11 * Retains the object on construction/assignment and releases it on
12 * destruction, exactly like a \c __strong property under ARC. Using this
13 * wrapper instead of raw pointers eliminates the class of bugs where a
14 * constructor forgets to retain an autoreleased object while the destructor
15 * unconditionally releases it.
16 *
17 * Safe to use with \c nil: retaining and releasing \c nil are no-ops.
18 *
19 * \code
20 * ObjCStrong<NSWindow> m_window; // starts nil
21 * m_window = [NSApp windowWithWindowNumber: wid]; // retains
22 * m_window = nil; // releases old, holds nil
23 * // destructor releases automatically
24 * \endcode
25 */
26 template <typename T>
27 class ObjCStrong {
28 public:
29 ObjCStrong() : m_ptr(nil) {}
30
31 // Intentionally implicit: allows `m_member = [SomeClass ...]` naturally.
32 // NOLINTNEXTLINE(google-explicit-constructor)
33 ObjCStrong(T *ptr) : m_ptr([ptr retain]) {}
34
35 ~ObjCStrong() { [m_ptr release]; }
36
37 ObjCStrong(const ObjCStrong &other) : m_ptr([other.m_ptr retain]) {}
38
39 ObjCStrong &operator=(const ObjCStrong &other)
40 {
41 if (m_ptr != other.m_ptr) {
42 [m_ptr release];
43 m_ptr = [other.m_ptr retain];
44 }
45 return *this;
46 }
47
48 ObjCStrong &operator=(T *ptr)
49 {
50 if (m_ptr != ptr) {
51 [m_ptr release];
52 m_ptr = [ptr retain];
53 }
54 return *this;
55 }
56
57 T *get() const { return m_ptr; }
58 operator T *() const { return m_ptr; }
59 T *operator->() const { return m_ptr; }
60 explicit operator bool() const { return m_ptr != nil; }
61
62 private:
63 T *m_ptr;
64 };