tst_QScopeGuard: test if and how guard in optional<> works

It's a bit cumbersome, but works, in principle, using CTAD.

Pick-to: 6.6 6.5 6.2
Task-number: QTBUG-114200
Change-Id: Ib7354180e870a695a978edabf684aedfcf9d9ecc
Reviewed-by: Jarek Kobus <jaroslaw.kobus@qt.io>
This commit is contained in:
Marc Mutz 2023-06-05 07:38:55 +02:00
parent 8b4dbce54e
commit b08ddd2c4e

View File

@ -5,6 +5,8 @@
#include <QTest>
#include <QtCore/QScopeGuard>
#include <optional>
/*!
\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); });