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;
    }
    ...
    if(IsColorGraph(qhash[ID]){
      ColorGraph * b = dynamic_cast<ColorGraph *>(qhash[ID]);
      b->SetColor(QColor(Qt::red));
    }
    

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

    [Added code tags ~kshegunov]



  • Hi,

    it's just a cast, so no leak.

    -Michael.


  • 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

    Hi,

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


Log in to reply