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 <jaroslaw.kobus@qt.io>
(cherry picked from commit b08ddd2c4ecedccd0bc08e9f2390a7b86ed861f4)
Reviewed-by: Qt Cherry-pick Bot <cherrypick_bot@qt-project.org>
This commit is contained in:
Marc Mutz 2023-06-05 07:38:55 +02:00 committed by Qt Cherry-pick Bot
parent a83d59b901
commit f732833eaa

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); });