Reputation: 656
I have QMap
that stores objects and I want to store pointers to these objects for some external processing. Will the pointer to the object remain valid after inserting/deleting some values from map? To illustrate:
QMap <QString, QString> map;
map.insert("one", "one");
map.insert("two", "two");
map.insert("three", "three");
QString *pointer = &map["one"];
qDebug()<<*pointer;
map.insert("aaa", "aaa");
map.insert("bbb", "bbb");
qDebug()<<*pointer;
map.insert("zzz", "zzz");
map.insert("xxx", "xxx");
qDebug()<<*pointer;
Is it guaranteed that pointer
will point to the exact same object after any number of insertions/deletions (considering of course that this object was not removed)
Or should I consider storing pointers instead of objects?
Upvotes: 1
Views: 537
Reputation: 49309
Doing a minor modification to your code:
QMap <QString, QString> map;
map.insert("one", "one");
map.insert("two", "two");
map.insert("three", "three");
QString *pointer = &map["one"];
qDebug()<<pointer;
map.insert("aaa", "aaa");
map.insert("bbb", "bbb");
pointer = &map["one"];
qDebug()<<pointer;
map.insert("zzz", "zzz");
map.insert("xxx", "xxx");
pointer = &map["one"];
qDebug()<<pointer;
reveals that it looks like it remains valid.
QMap
elements are sorted as they are inserted. The underlying data structure is a red-black tree (in Qt5 at least, IIRC it was a skip list in Qt4). Nodes are evidently stored on the heap rather than pools, as it doesn't come with a reserve(space)
method, which would only be applicable if it used pools.
There is no good reason for a tree node to be reallocated to another memory location, as the tree structure is easily redefined by changing leaf pointer values.
So yeah, pointers should persist as the map changes, as long as that particular key entry is not removed.
Upvotes: 1