QHash & dynamic_cast & memory leak

  • Hi
    I have dynamic creation of widgets that I appending in QHash<int,QWidget*>
    is this good valid approach?

    bool CLASS::IsColorGraph(const QWidget * widget)
       return dynamic_cast<const ColorGraph*>(widget) != 0;
      ColorGraph * b = dynamic_cast<ColorGraph *>(qhash[ID]);

    what will heppen with b pointer? is it memory leak?

    [Added code tags ~kshegunov]

  • Hi,

    it's just a cast, so no leak.


  • Qt Champions 2016

    @ask4 said in QHash & dynamic_cast & memory leak:

    what will heppen with b pointer? is it memory leak?

    The pointer will be freed when the stack unwinds, and as a consequence the pointer can't be leaked.

    ColorGraph * b = dynamic_cast<ColorGraph *>(qhash[ID]);

    As you already know that the type of that element is ColorGraph you can reinterpret_cast the pointer safely at that point, although the "gain" would be that you skip one lookup through the virtual table, which is practically nothing.

  • Lifetime Qt Champion


    To add to my fellows, since you are dealing with QObject based classes, you should use qobject_cast.

  • thanks lads!

Log in to reply

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