Chatterino
QObjectRef.hpp
Go to the documentation of this file.
1 #pragma once
2 
3 #include <QApplication>
4 #include <QObject>
5 #include <type_traits>
6 
7 namespace chatterino {
10 template <typename T>
12 {
13 public:
15  {
16  static_assert(std::is_base_of_v<QObject, T>);
17  }
18 
19  explicit QObjectRef(T *t)
20  {
21  static_assert(std::is_base_of_v<QObject, T>);
22 
23  this->set(t);
24  }
25 
26  QObjectRef(const QObjectRef &other)
27  {
28  this->set(other.t_);
29  }
30 
32  {
33  this->set(nullptr);
34  }
35 
37  {
38  this->set(t);
39 
40  return *this;
41  }
42 
43  operator bool()
44  {
45  return t_;
46  }
47 
49  {
50  return t_;
51  }
52 
53  T *get()
54  {
55  return t_;
56  }
57 
58 private:
59  void set(T *other)
60  {
61  // old
62  if (this->conn_)
63  {
64  QObject::disconnect(this->conn_);
65  }
66 
67  // new
68  if (other)
69  {
70  // the cast here should absolutely not be necessary, but gcc still requires it
71  this->conn_ =
72  QObject::connect((QObject *)other, &QObject::destroyed, qApp,
73  [this](QObject *) {
74  this->set(nullptr);
75  },
76  Qt::DirectConnection);
77  }
78 
79  this->t_ = other;
80  }
81 
82  std::atomic<T *> t_{};
83  QMetaObject::Connection conn_;
84 };
85 } // namespace chatterino
QObjectRef(const QObjectRef &other)
Definition: QObjectRef.hpp:26
QObjectRef & operator=(T *t)
Definition: QObjectRef.hpp:36
Definition: Application.cpp:48
QObjectRef(T *t)
Definition: QObjectRef.hpp:19
Definition: QObjectRef.hpp:11
~QObjectRef()
Definition: QObjectRef.hpp:31
T * operator->()
Definition: QObjectRef.hpp:48
QObjectRef()
Definition: QObjectRef.hpp:14