简体   繁体   中英

Will pointer to an element in QMap remain valid after inserting some more elements in the map?

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM