Const pointer Map and Hash issue
-
wrote on 17 Jan 2024, 08:57 last edited by
I have a problem understanding QMap and QHash. I have already read that QMap provides a copy of the content and not a pointer / reference.
QMap<int, TextItem> items; items.insert(0, TextItem()); items.insert(1, TextItem());
Do I still get a pointer to the content that I can use with this statement - it gives no compiler error?
TextItem a = items.value(0); TextItem* b = &a;
This not
TextItem* c = &items.value(0);
Error is - a value from type const TextItem* could not use to initialize a entity of type TextItem*.
It works with QList, it must be a special feature of QMap.
-
I have a problem understanding QMap and QHash. I have already read that QMap provides a copy of the content and not a pointer / reference.
QMap<int, TextItem> items; items.insert(0, TextItem()); items.insert(1, TextItem());
Do I still get a pointer to the content that I can use with this statement - it gives no compiler error?
TextItem a = items.value(0); TextItem* b = &a;
This not
TextItem* c = &items.value(0);
Error is - a value from type const TextItem* could not use to initialize a entity of type TextItem*.
It works with QList, it must be a special feature of QMap.
@astoffregen said in Const pointer Map and Hash issue:
TextItem* c = &items.value(0);
Apart from a possible compiler error this will result in a dangling pointer as the returned object is destroyed after the semicolon.
Wrt the error I would guess you use Qt5 where QMap::value() returns a const object as you can see in the documentation: https://doc.qt.io/qt-5/qmap.html#value
1/2