QPainterStateGuard: also check for nullptr painter in save(), restore()

The ctor refuses to be called with a nullptr painter, but a moved-from
QPainterStateGuard object _will_ have a nullptr painter. An assert
gives a slightly nicer error message than "nullptr deref".

Extract Method verifyPainter() to not litter the executable with
string literals for every one of the these functions (some compilers
don't use the leeway extended to them by the standard to fold duplicate
string literals).

Found in API-review.

Amends ec3a5f4994a2bafc65fa8e01fb0861219580f622.

Pick-to: 6.9
Change-Id: I562e6a0ff5a4c8ce86418b998ed78c501441b61a
Reviewed-by: Giuseppe D'Angelo <giuseppe.dangelo@kdab.com>
Reviewed-by: Axel Spoerl <axel.spoerl@qt.io>
Reviewed-by: Juha Vuolle <juha.vuolle@qt.io>
This commit is contained in:
Marc Mutz 2025-01-30 12:09:01 +01:00
parent d6025aa054
commit 5c20f9aa5c

View File

@ -33,7 +33,7 @@ public:
explicit QPainterStateGuard(QPainter *painter, InitialState state = InitialState::Save)
: m_painter(painter)
{
Q_ASSERT(painter);
verifyPainter();
if (state == InitialState::Save)
save();
}
@ -46,18 +46,25 @@ public:
void save()
{
verifyPainter();
m_painter->save();
++m_level;
}
void restore()
{
verifyPainter();
Q_ASSERT(m_level > 0);
--m_level;
m_painter->restore();
}
private:
void verifyPainter()
{
Q_ASSERT(m_painter);
}
QPainter *m_painter;
int m_level = 0;
};