Guard sentinels for slots?



  • Back in the Qt4 days I occasionally ran across references that recommended a guard around slots to prohibit the slot from being recursively called. Here's a quick implementation:

    MyQObject::MySlot() {
        static bool inSlot(false);    // probably better to make this a member variable
        if (!inSlot) {
            inSlot = true;
            // *** do important slot stuff ***
            // maybe emit signals that in a round-about way 
            // cause this slot to be executed again?
            inSlot = false;
        }
    }
    

    Is this still a thing? Does Qt5 have any internal checks to make this kind of blocking redundant? Being an admittedly paranoid person, I still frequently do this to protect from signal/slot loops causing a stack overflow.

    What's the best practice and caveats these days?


  • Moderators

    @Kent-Dorfman said in Guard sentinels for slots?:

    Does Qt5 have any internal checks to make this kind of blocking redundant?

    I don't think so.

    The techniques you used in Qt 4 are still valid for Qt 5.



  • @Kent-Dorfman
    As @JKSH says you are still responsible for writing explicit code if you want this check. Doubtless you're well aware already, but (a) you could have this in debug/development code only if you trust to skip it in production and (b) personally in some shape or form I'd implement via, say, a function-scoped local variable whose constructor sets and destructor clears the inSlot so that you don't have to worry about putting a return in the middle of your code or an exception being raised etc.


Log in to reply
 

Looks like your connection to Qt Forum was lost, please wait while we try to reconnect.