Qt6 topics merged with General

static_cast for downcasting Event

  • I have a code like this:

    void CellInputHandler::handleMouseButtonReleaseEvents(
            QObject *watched, QEvent *event)
        auto mouseEvent = static_cast<QMouseEvent*>(event);

    Now if I run Clang-Tidy it complains that i should use dynamic_cast. However even in some offical examples for stuff like this i saw example still with static_cast. Doesn't it slice the object and should be dynamic_cast or even qobject_cast ?

  • Moderators

    You shouldn't do that. Can you show an official example that does that? All places I've seen deal with a pointer to event and there's no problem with static_casting that. Apart from the slicing your example copies the event in the parameter, which is also a bad thing, as events are usually an in-out parameter, meaning you modify them (e.g. calling accept() or reject() on them). Passing them by value doesn't really make sense.

  • your'e right we just cast the pointer here. And still clan complains i should use dynamic_cast ...

  • Moderators

    Ah, sorry, the forum formatting ate the stars :) I fixed that for you. Please place code between ``` to make it format like code.

    Well technically it could be an invalid cast in some circumstances, as you could cast to an unrelated type, but if you check the type of the event before you cast (which you should anyway) there's no problem. dynamic_cast is kinda expensive so doing an if + static_cast for types you know it's ok for is just cheaper, but static analysis tools won't like it. I'd say it's safe to say it's a false positive in this case. The tool just can't know better.

  • And what about q_object_cast? I read it should be a lot faster than dynamic_cast. Of course I think youre right static_cast should be faster still since theres no real check.

  • Moderators

    qobject_cast works with classes that derive from QObject and have the Q_OBJECT macro. QEvent is a simple "data" class and it does not derive from QObject so qobject_cast can't be used for it.

Log in to reply