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) | |
void | dismiss() |
相关非成员
QScopeGuard<typename std::decay<F>::type> | qScopeGuard(F &&f) |
详细说明
QScopeGuard<F> 是一个类,其唯一目的是在其析构函数中运行函数f 。无论函数是正常退出、通过返回语句提前退出还是通过异常退出,该类都能保证您的清理代码得到执行。
注意: 不支持异常。可调用函数在执行、复制或移动时不应抛出异常。
另请参阅 QScopedValueRollback 。
成员函数文档
[explicit noexcept]
QScopeGuard::QScopeGuard(F &&f)
[explicit noexcept]
QScopeGuard::QScopeGuard(const F &f)
创建一个作用域防护,在作用域结束时执行f 。
如果F是 lambda,则无法写入其类型。在这种情况下,您需要依靠类模板参数演绎(C++17 特性)来完全省略模板参数,或者使用辅助函数qScopeGuard() 代替此构造函数。
[noexcept]
void QScopeGuard::dismiss()
解除作用域防护,这样就不会在作用域结束时调用函数F。
相关非成员
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; (...) }
© 2025 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.