Fcitx
trackableobject.h
Go to the documentation of this file.
1 /*
2  * SPDX-FileCopyrightText: 2016-2016 CSSlayer <wengxt@gmail.com>
3  *
4  * SPDX-License-Identifier: LGPL-2.1-or-later
5  *
6  */
7 #ifndef _FCITX_UTILS_TRACKABLEOBJECT_H_
8 #define _FCITX_UTILS_TRACKABLEOBJECT_H_
9 
10 /// \addtogroup FcitxUtils
11 /// \{
12 /// \file
13 /// \brief Utitliy classes for statically tracking the life of a object.
14 
15 #include <memory>
16 #include <type_traits>
17 #include <utility>
18 #include <fcitx-utils/handlertable.h>
19 #include <fcitx-utils/macros.h>
20 
21 namespace fcitx {
22 
23 template <typename T>
25 
26 /// \brief Utility class provides a weak reference to the object.
27 ///
28 /// Not thread-safe.
29 template <typename T>
31  friend class TrackableObject<std::remove_const_t<T>>;
32 
33 public:
34  TrackableObjectReference() : rawThat_(nullptr) {}
35  FCITX_INLINE_DEFINE_DEFAULT_DTOR_COPY_AND_MOVE(TrackableObjectReference)
36 
37  /// \brief Check if the reference is still valid.
38  bool isValid() const { return !that_.expired(); }
39 
40  /// \brief Check if the reference is not tracking anything.
41  bool isNull() const { return rawThat_ == nullptr; }
42 
43  /// \brief Get the referenced object. Return nullptr if it is not available.
44  T *get() const { return that_.expired() ? nullptr : rawThat_; }
45 
46  /// \brief Reset reference to empty state.
47  void unwatch() {
48  that_.reset();
49  rawThat_ = nullptr;
50  }
51 
52 private:
53  TrackableObjectReference(std::weak_ptr<bool> that, T *rawThat)
54  : that_(std::move(that)), rawThat_(rawThat) {}
55 
56  std::weak_ptr<bool> that_;
57  T *rawThat_;
58 };
59 
60 /// \brief Helper class to be used with TrackableObjectReference
61 ///
62 /// One need to subclass it to make use of it.
63 /// \code{.cpp}
64 /// class Object : TrackableObject<Object> {};
65 ///
66 /// Object obj; auto ref = obj.watch();
67 /// \endcode
68 /// \see TrackableObjectReference
69 template <typename T>
70 class TrackableObject {
71 public:
73  : self_(std::make_unique<std::shared_ptr<bool>>(
74  std::make_shared<bool>())) {}
75  TrackableObject(const TrackableObject &) = delete;
76  virtual ~TrackableObject() = default;
77 
79  return TrackableObjectReference<T>(*self_, static_cast<T *>(this));
80  }
81 
82  TrackableObjectReference<const T> watch() const {
84  static_cast<const T *>(this));
85  }
86 
87 private:
88  std::unique_ptr<std::shared_ptr<bool>> self_;
89 };
90 } // namespace fcitx
91 
92 #endif // _FCITX_UTILS_TRACKABLEOBJECT_H_
Utility class provides a weak reference to the object.
void unwatch()
Reset reference to empty state.
Definition: action.cpp:17
bool isValid() const
Check if the reference is still valid.
Helper class to be used with TrackableObjectReference.
bool isNull() const
Check if the reference is not tracking anything.