File indexing completed on 2024-04-28 15:40:25

0001 /* SPDX-FileCopyrightText: 2003-2010 Jesper K. Pedersen <blackie@kde.org>
0002 
0003    SPDX-License-Identifier: GPL-2.0-or-later
0004 */
0005 #include "BooleanGuard.h"
0006 
0007 /**
0008    \class Utilities::BooleanGuard
0009    \brief Guard that controls entry using a static variable
0010 
0011    Sometimes you can get into trouble where a function calls another, which
0012    indirectly calls the first one again, resulting in an endless
0013    loop. paintEvent() and resizeEvent() are example of places where this
0014    sometimes happens.
0015 
0016    A solution is to use a static bool as a guard controlling whether the
0017    function is already in action. This may look like this:
0018    <pre>
0019    void f() {
0020       static bool guard = false;
0021       if ( guard )
0022         return;
0023       guard = true;
0024       ...
0025       guard = false;
0026    }
0027    </pre>
0028    This code of course have the problem that the guard is not correctly
0029    unset, if there is a premature return() in the code. This class solves
0030    this, and the code will look like this:
0031 
0032    <pre>
0033    void f() {
0034        static bool inAction = false;
0035        BooleanGuard guard( inAction );
0036        if ( !guard.canContinue() )
0037            return;
0038 
0039        ...
0040    }
0041    </pre>
0042 **/
0043 
0044 Utilities::BooleanGuard::BooleanGuard(bool &guard)
0045     : m_guard(guard)
0046 {
0047     if (m_guard == false) {
0048         m_iLockedIt = true;
0049         m_guard = true;
0050     } else
0051         m_iLockedIt = false;
0052 }
0053 
0054 Utilities::BooleanGuard::~BooleanGuard()
0055 {
0056     if (m_iLockedIt)
0057         m_guard = false;
0058 }
0059 
0060 bool Utilities::BooleanGuard::canContinue()
0061 {
0062     return m_iLockedIt;
0063 }
0064 // vi:expandtab:tabstop=4 shiftwidth=4: