2017-07-18 44 views
0

我有QMap存儲對象,我想存儲指向這些對象的指針進行一些外部處理。在從地圖插入/刪除一些值後,指向該對象的指針是否仍然有效?爲了說明:在地圖中插入更多元素之後,指向QMap中元素的指針是否仍然有效?

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; 

能夠保證所有的pointer將任意數量的插入/缺失後指向完全相同的對象(這個對象沒有被去除,當然考慮)

或者,我應該考慮存儲指針而不是對象?

+0

地圖中的值是按值存儲的,即使在這種情況下,它意味着指針(它指向的地址)按值存儲[例如](https://stackoverflow.com/questions/14340672/invalidate- pointer-values-inside-a-qmap) –

+0

你有沒有考慮過使用'std :: map'呢?標準容器的失效規則已經過詳細記錄,並且通常可以理解。 –

+0

[此鏈接](http://doc.qt.io/qt-5/qmap-iterator.html#details)表示在'QMap'中插入不會使迭代器失效。 *「如果向地圖添加項目,現有迭代器將保持有效。」*很可能指向現有元素的指針也被保留,但沒有明確說明。 –

回答

1

做一個小的修改代碼:

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; 

表明,它看起來仍然有效。

QMap元素按插入的順序排序。底層的數據結構是紅黑樹(至少在Qt5中,IIRC是Qt4中的跳過列表)。顯然,節點存儲在堆而不是池中,因爲它不包含reserve(space)方法,只有在使用池時才適用。

樹節點沒有很好的理由被重新分配到另一個內存位置,因爲通過改變葉指針值很容易重新定義樹結構。

所以是的,指針應該在地圖發生變化時持續下去,只要該特定的鍵入不被刪除。

相關問題