How to know if the QHash::insert(const Key &key, const T &value) succeeded or failed



  • The documentation says nothing about this.



  • @eMan.Lived
    Hi,

    Based on QHash size you can know value is inserted or not.
    if inserted size becomes +1 to previous size if not size remains same as previous size.

    int mapSize;
    QHash<key,value> hash;
    mapSize = hash.size();

    hash.insert(key,Value);
    if(hash.size()==mapSize+1)
    {
    //inserted succeeded
    mapSize = hash.size();

    }else{
    //insertFailed
    }


  • Moderators

    @eMan.Lived insert() returns an iterator. I'm not sure (and documentation really does not say anything about it!), but I think if insertion fails the iterator will be hash.end(), otherwise it will point to the just inserted pair. You can check Qt source code to find out what really happens.



  • @Venkatesh-V
    Hello,
    It looks like the developers have forgotten something. I mean that it looks more clear like this:

    QHash<key, value> hash;
    if (hash.insert(Key, Value) == hash.end())
    {
      // failed
    }
    else
    {
      // succeeded
    }
    

    Well, thanks for the workaround.

    @jsulm
    Hello,
    I've looked source code.

    1. QHash::insert() just return result of called QHash::insertMulti() (line 1011).
    2. QHash::insertMulti(), in turn, returns an iterator, in the constructor of which the result of calling function createNode() is passed (line 781).
    3. createNode() returns a pointer to the Node created by the new operator (lines 548, 551).

    As you can see there is no check for successful memory allocation. Maybe throws an exception?


  • Moderators

    @eMan.Lived Well, in case memory cannot be allocated there will be an exception and the application will be closed by the OS.


Log in to reply
 

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