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/qtclasshelpermacros.h>
9#include <QtCore/qcompilerdetection.h>
10#include <QtCore/qtconfigmacros.h>
11
12#include <type_traits>
13#include <utility>
14
15QT_BEGIN_NAMESPACE
16
17template <typename F>
18class QScopeGuard
19{
20public:
21 Q_NODISCARD_CTOR
22 explicit QScopeGuard(F &&f) noexcept
23 : m_func(std::move(f))
24 {
25 }
26
27 Q_NODISCARD_CTOR
28 explicit QScopeGuard(const F &f) noexcept
29 : m_func(f)
30 {
31 }
32
33 Q_NODISCARD_CTOR
34 QScopeGuard(QScopeGuard &&other) noexcept
35 : m_func(std::move(other.m_func))
36 , m_invoke(std::exchange(obj&: other.m_invoke, new_val: false))
37 {
38 }
39
40 ~QScopeGuard() noexcept
41 {
42 if (m_invoke)
43 m_func();
44 }
45
46 void dismiss() noexcept
47 {
48 m_invoke = false;
49 }
50
51private:
52 Q_DISABLE_COPY(QScopeGuard)
53
54 F m_func;
55 bool m_invoke = true;
56};
57
58template <typename F> QScopeGuard(F(&)()) -> QScopeGuard<F(*)()>;
59
60//! [qScopeGuard]
61template <typename F>
62[[nodiscard]] QScopeGuard<typename std::decay<F>::type> qScopeGuard(F &&f)
63{
64 return QScopeGuard<typename std::decay<F>::type>(std::forward<F>(f));
65}
66
67QT_END_NAMESPACE
68
69#endif // QSCOPEGUARD_H
70

source code of qtbase/src/corelib/tools/qscopeguard.h