Back to home page

EIC code displayed by LXR

 
 

    


File indexing completed on 2026-09-25 09:24:21

0001 // Copyright (C) 2018 Klarälvdalens Datakonsult AB, a KDAB Group company, info@kdab.com, author Sérgio Martins <sergio.martins@kdab.com>
0002 // Copyright (C) 2019 The Qt Company Ltd.
0003 // SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
0004 // Qt-Security score:significant reason:default
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; // do it before we may throw from calling m_func()
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 //! [qScopeGuard]
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 // QSCOPEGUARD_H