Search code examples
c++listqtappendqlist

Appending QList to QList<QList>


I have an interesting problem with Qt Qlist container. Trying to append QList to QList makes my iterator to point to unknown part of memory.

QList<int> listSmall;
QList<QList<int>> listBig;

for(int i = 0; i < 3; ++i)
    listSmall.append(i);

for(auto it = listSmall.begin(); it != listSmall.end(); ++it)
    listBig.append(listSmall);

Condition it != listSmall.end(); always true if i append small list to big. Why does this happen?

P.S. STL list works just fine.


Solution

  • This is a known limitation of Qt containers when used with stl-like iterators. The documentation explains it.

    Implicit sharing has another consequence on STL-style iterators: you should avoid copying a container while iterators are active on that container. The iterators point to an internal structure, and if you copy a container you should be very careful with your iterators.

    I am afraid you will have to find a different way of doing what you are trying to do (like using a standard list or iterate differently).