QScopeGuard 类

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

头: #include <QScopeGuard>
qmake: QT += core
Since: Qt 5.12

公共函数

QScopeGuard (QScopeGuard<F> && other )
~QScopeGuard ()
void dismiss ()
QScopeGuard<F> qScopeGuard (F f )

详细描述

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

成员函数文档编制

QScopeGuard:: QScopeGuard ( QScopeGuard < F > && other )

Default constructs an instance of QScopeGuard.

QScopeGuard:: ~QScopeGuard ()

Destroys the instance of QScopeGuard.

void QScopeGuard:: dismiss ()

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

相关非成员

QScopeGuard < F > qScopeGuard ( F f )

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

QScopeGuard <F> is a class which sole purpose is to run a 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.

F is a lambda then you cannot instantiate the template directly, therefore the qScopeGuard() helper is provided and QScopeGuard <F> is made a private implementation detail.

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;
    (...)
}
					

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

另请参阅 QScopedValueRollback .