Solved 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
} -
@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.QHash::insert()
just return result of calledQHash::insertMulti()
(line 1011).QHash::insertMulti()
, in turn, returns an iterator, in the constructor of which the result of calling functioncreateNode()
is passed (line 781).createNode()
returns a pointer to theNode
created by thenew
operator (lines 548, 551).
As you can see there is no check for successful memory allocation. Maybe throws an exception?
-
@eMan.Lived Well, in case memory cannot be allocated there will be an exception and the application will be closed by the OS.