QScopeGuard 类

template <typename F> class QScopeGuard

提供用于在作用域结束时调用函数的作用域守卫。 更多...

头: #include <QScopeGuard>
CMake: find_package(Qt6 COMPONENTS Core REQUIRED)
target_link_libraries(mytarget PRIVATE Qt6::Core)
qmake: QT += core
Since: Qt 5.12

公共函数

  QScopeGuard (const F & f )
  QScopeGuard (F && f )
void dismiss ()
QScopeGuard<typename std::decay<F>::type> qScopeGuard (F && f )

详细描述

QScopeGuard<F> is a class of which the sole purpose is to run the function f in its destructor. This is useful for guaranteeing your cleanup code is executed, whether the function is exited normally, exited early by a return statement, or exited by an exception.

注意: Exceptions are not supported. The callable shouldn't throw when executed, copied or moved.

另请参阅 QScopedValueRollback .

成员函数文档编制

[since 5.15] QScopeGuard:: QScopeGuard ( F && f )

[since 5.15] QScopeGuard:: QScopeGuard (const F & f )

Create a scope guard that will execute f at the end of the scope.

F is a lambda, its type cannot be written. In that case you need to either rely on class template argument deduction (C++17 feature) and leave the template parameter out completely or use the helper function qScopeGuard () instead of this constructor.

该函数在 Qt 5.15 引入。

void QScopeGuard:: dismiss ()

Disarms the scope guard, so that the function F will not be called at the end of the scope.

相关非成员

template <typename F> QScopeGuard < typename std::decay < F > ::type > qScopeGuard ( F && f )

The qScopeGuard function can be used to call a function at the end of the scope.

Create a scope guard that will execute f at the end of the scope.

This helper function is provided so that you can easily construct a QScopeGuard without having to name the template parameter for the type of the callable. If F is a lambda then you cannot write its type and relying on this helper or class template argument deduction is necessary.

Example usage is as follows:

void myComplexCodeWithMultipleReturnPoints(int v)
{
    // The lambda will be executed right before your function returns
    auto cleanup = qScopeGuard([] { code you want executed goes HERE; });
    if (v == -1)
        return;
    int v2 = code_that_might_throw_exceptions();
    if (v2 == -1)
        return;
    (...)
}