File indexing completed on 2026-09-25 09:24:21
0001
0002
0003
0004
0005
0006 #ifndef QSCOPEGUARD_H
0007 #define QSCOPEGUARD_H
0008
0009 #include <QtCore/qassert.h>
0010 #include <QtCore/qtclasshelpermacros.h>
0011 #include <QtCore/qcompilerdetection.h>
0012 #include <QtCore/qtconfigmacros.h>
0013
0014 #include <type_traits>
0015 #include <utility>
0016
0017 class tst_QScopeGuard;
0018
0019 QT_BEGIN_NAMESPACE
0020
0021 template <typename F>
0022 class QScopeGuard
0023 {
0024 public:
0025 Q_NODISCARD_CTOR
0026 explicit QScopeGuard(F &&f) noexcept
0027 : m_func(std::move(f))
0028 {
0029 }
0030
0031 Q_NODISCARD_CTOR
0032 explicit QScopeGuard(const F &f) noexcept
0033 : m_func(f)
0034 {
0035 }
0036
0037 Q_NODISCARD_CTOR
0038 QScopeGuard(QScopeGuard &&other) noexcept
0039 : m_func(std::move(other.m_func))
0040 , m_invoke(std::exchange(other.m_invoke, false))
0041 {
0042 }
0043
0044 ~QScopeGuard() noexcept
0045 {
0046 if (m_invoke)
0047 m_func();
0048 }
0049
0050 void dismiss() noexcept
0051 {
0052 m_invoke = false;
0053 }
0054
0055 void commit() noexcept(std::is_nothrow_invocable_v<F>)
0056 {
0057 Q_ASSERT(m_invoke);
0058 m_invoke = false;
0059 m_func();
0060 }
0061
0062 private:
0063 Q_DISABLE_COPY(QScopeGuard)
0064 friend class ::tst_QScopeGuard;
0065
0066 F m_func;
0067 bool m_invoke = true;
0068 };
0069
0070 template <typename F> QScopeGuard(F(&)()) -> QScopeGuard<F(*)()>;
0071
0072
0073 template <typename F>
0074 [[nodiscard]] QScopeGuard<typename std::decay<F>::type> qScopeGuard(F &&f)
0075 {
0076 return QScopeGuard<typename std::decay<F>::type>(std::forward<F>(f));
0077 }
0078
0079 QT_END_NAMESPACE
0080
0081 #endif