本页内容

QScopeGuard Class

template <typename F> class QScopeGuard

提供了一个作用域保护机制,用于在作用域末尾调用函数。更多内容...

标题: #include <QScopeGuard>
CMake: find_package(Qt6 REQUIRED COMPONENTS Core)
target_link_libraries(mytarget PRIVATE Qt6::Core)
qmake: QT += core

公共函数

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

详细说明

QScopeGuard<F> 是一个模板类,其中F 是将在析构函数中调用的可调用对象(如函数指针、 functor 或 lambda)的类型。 这有助于确保您的清理代码能够被执行,无论函数是正常退出、通过 return 语句提前退出,还是因异常而退出。

可以通过dismiss() 禁用作用域守护,在这种情况下,函数将完全不被执行;或者通过commit() 在销毁之前执行该函数。

注意: 不支持异常 。可调用对象在执行、复制或移动时不应抛出异常。

另请参阅 QScopedValueRollback 。

成员函数文档

[explicit noexcept] QScopeGuard::QScopeGuard(F &&f)

[explicit noexcept] QScopeGuard::QScopeGuard(const F &f)

创建一个作用域守护,它将在作用域结束时执行f 。

如果F是 lambda 表达式,则无法指定其类型。在这种情况下,您需要要么依赖类模板参数推导(C++17 特性)并完全省略模板参数,要么使用辅助函数qScopeGuard() 代替此构造函数。

[noexcept(...), since 6.11] void QScopeGuard::commit()

调用函数F,然后解除作用域守护的启用状态。调用此函数时,守护必须处于启用状态(即尚未调用dismiss())。

该函数在 Qt 6.11 中引入。

注意: 当std::is_nothrow_invocable_v<F> 为true 时,此 函数为 noexcept。

另请参阅 dismiss()。

[noexcept] void QScopeGuard::dismiss()

禁用作用域保护,从而确保函数F不会在作用域结束时被调用。

另请参阅 commit()。

相关的非成员

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

qScopeGuard 函数可用于在作用域结束时调用某个函数。

创建一个作用域守护,该守护将在作用域结束时执行f 。

提供此辅助函数,以便您能够轻松构建 `QScopeGuard `,而无需为可调用对象的类型命名模板参数。如果`F`是 lambda,则无法直接写出其类型,此时必须依赖此辅助函数或类模板参数推导。

使用示例如下:

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;

    //...
}

© 2026 The Qt Company Ltd. Documentation contributions included herein are the copyrights of their respective owners. The documentation provided herein is licensed under the terms of the GNU Free Documentation License version 1.3 as published by the Free Software Foundation. Qt and respective logos are trademarks of The Qt Company Ltd. in Finland and/or other countries worldwide. All other trademarks are property of their respective owners.