Allocating memory in Desctructor for deleting QHash values



  • Hello ! :)

    is there a QHash method which returns one key or its hashed value (as a reference)?

    I attempt to delete objects stored as values in a QHash in the Destructor of a class of mine.

    I only found the method keys() to get all keys of the hash which requires allocating a QList, or don't I have to allocate a QList?

    If the keys() method fails due to memory constraints, I can't destruct my class, (because I don't get the keys which I need to find the values to delete) or can I ?

    Or is there an other approach to this kind of destructing?

    Thank you for your attempt and Best Regards!


  • Moderators

    You can go thorough all values with:
    @
    QHashIterator<QString, int> i(hash);
    while (i.hasNext()) {
    i.next();
    cout << i.key() << ": " << i.value() << endl;
    }
    @

    As mentioned in - surprise! - "official documentation":http://qt-project.org/doc/qt-5.0/qtcore/qhash.html. Also, remember that if your values are QObject pointers that are properly parented, you don't need to delete them, Qt will do it for you.



  • Yes, I read that. Does creating the QHashIterator not allocate memory?
    The values are of a custom-made class. Can I read up on the benefit of deriving of QObject somewhere? Where?
    Thank you.


  • Moderators

    I'm not sure. Probably it's already allocated when you create the hash. Take a look at the code if you are so inclined, or use a profiler to see what happens at runtime.

    "QObject":http://qt-project.org/doc/qt-4.8/metaobjects.html stuff is here. It does introduce overhead, so if your device is low on memory and you have a lot of objects to create, then maybe it's not a good idea.


Log in to reply
 

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