From f732833eaa4b9beca5d9cc742af59ff80edacfe3 Mon Sep 17 00:00:00 2001 From: Marc Mutz Date: Mon, 5 Jun 2023 07:38:55 +0200 Subject: [PATCH] tst_QScopeGuard: test if and how guard in optional<> works It's a bit cumbersome, but works, in principle, using CTAD. Task-number: QTBUG-114200 Change-Id: Ib7354180e870a695a978edabf684aedfcf9d9ecc Reviewed-by: Jarek Kobus (cherry picked from commit b08ddd2c4ecedccd0bc08e9f2390a7b86ed861f4) Reviewed-by: Qt Cherry-pick Bot --- .../tools/qscopeguard/tst_qscopeguard.cpp | 21 +++++++++++++++++++ 1 file changed, 21 insertions(+) diff --git a/tests/auto/corelib/tools/qscopeguard/tst_qscopeguard.cpp b/tests/auto/corelib/tools/qscopeguard/tst_qscopeguard.cpp index 015cbcc0e74..ac6551645f7 100644 --- a/tests/auto/corelib/tools/qscopeguard/tst_qscopeguard.cpp +++ b/tests/auto/corelib/tools/qscopeguard/tst_qscopeguard.cpp @@ -5,6 +5,8 @@ #include #include +#include + /*! \class tst_QScopeGuard \internal @@ -20,6 +22,7 @@ private Q_SLOTS: void construction(); void constructionFromLvalue(); void constructionFromRvalue(); + void optionalGuard(); void leavingScope(); void exceptions(); }; @@ -117,6 +120,24 @@ void tst_QScopeGuard::constructionFromRvalue() QCOMPARE(Callable::moved, 1); } +void tst_QScopeGuard::optionalGuard() +{ + int i = 0; + auto lambda = [&] { ++i; }; + std::optional sg = false ? std::optional{qScopeGuard(lambda)} : std::nullopt; + QVERIFY(!sg); + QCOMPARE(i, 0); + sg.emplace(qScopeGuard(lambda)); + QVERIFY(sg); + sg->dismiss(); + sg.reset(); + QCOMPARE(i, 0); + sg.emplace(qScopeGuard(lambda)); + QCOMPARE(i, 0); + sg.reset(); + QCOMPARE(i, 1); +} + void tst_QScopeGuard::leavingScope() { auto cleanup = qScopeGuard([] { s_globalState++; QCOMPARE(s_globalState, 3); });