1 | // Copyright (C) 2018 Klarälvdalens Datakonsult AB, a KDAB Group company, info@kdab.com, author Sérgio Martins <sergio.martins@kdab.com> |
2 | // Copyright (C) 2019 The Qt Company Ltd. |
3 | // SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only |
4 | |
5 | #ifndef QSCOPEGUARD_H |
6 | #define QSCOPEGUARD_H |
7 | |
8 | #include <QtCore/qglobal.h> |
9 | |
10 | #include <type_traits> |
11 | #include <utility> |
12 | |
13 | QT_BEGIN_NAMESPACE |
14 | |
15 | template <typename F> |
16 | class QScopeGuard |
17 | { |
18 | public: |
19 | Q_NODISCARD_CTOR |
20 | explicit QScopeGuard(F &&f) noexcept |
21 | : m_func(std::move(f)) |
22 | { |
23 | } |
24 | |
25 | Q_NODISCARD_CTOR |
26 | explicit QScopeGuard(const F &f) noexcept |
27 | : m_func(f) |
28 | { |
29 | } |
30 | |
31 | Q_NODISCARD_CTOR |
32 | QScopeGuard(QScopeGuard &&other) noexcept |
33 | : m_func(std::move(other.m_func)) |
34 | , m_invoke(std::exchange(other.m_invoke, false)) |
35 | { |
36 | } |
37 | |
38 | ~QScopeGuard() noexcept |
39 | { |
40 | if (m_invoke) |
41 | m_func(); |
42 | } |
43 | |
44 | void dismiss() noexcept |
45 | { |
46 | m_invoke = false; |
47 | } |
48 | |
49 | private: |
50 | Q_DISABLE_COPY(QScopeGuard) |
51 | |
52 | F m_func; |
53 | bool m_invoke = true; |
54 | }; |
55 | |
56 | template <typename F> QScopeGuard(F(&)()) -> QScopeGuard<F(*)()>; |
57 | |
58 | //! [qScopeGuard] |
59 | template <typename F> |
60 | [[nodiscard]] QScopeGuard<typename std::decay<F>::type> qScopeGuard(F &&f) |
61 | { |
62 | return QScopeGuard<typename std::decay<F>::type>(std::forward<F>(f)); |
63 | } |
64 | |
65 | QT_END_NAMESPACE |
66 | |
67 | #endif // QSCOPEGUARD_H |
68 | |