在本页

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 。无论函数是正常退出、被返回语句提前退出还是被异常退出,它都能保证您的清理代码得到执行。

使用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() ed)。

此函数在 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.