[Qt-interest] Iterators and implicitly shared containers

Ben Swerts benswerts at telenet.be
Fri Dec 17 19:22:27 CET 2010


Hello all,

I have the following piece of code (Qt 4.5.3):

#include <QtDebug>
#include <QVector>

int main()
{
  QVector<int> v1 = QVector<int>() << 1;
  QVector<int>::iterator it = v1.begin();
  const QVector<int> v2 = v1;

  *it = 2;
  //v1[0] = 2;

  qDebug() << "v1:" << v1 << ", v2:" << v2;
  return 0;
}

The output I expected:

	v1: QVector(2) , v2: QVector(1)

This is what I got:

	v1: QVector(2) , v2: QVector(2)

The detaching mechanism is not working when you create an iterator, create a
copy of the vector and modify the original through the iterator. There are
two ways to work around this:
- create the iterator after the copy
- use operator[] instead of the iterator

Is this behaviour as expected/by design? An STL container behaves
differently, obviously. It took me quite some time to figure out why a
vector was being changed behind my back.
If this is the expected behaviour, is there a way to force detachment?
I haven't tried Qt 4.7.1, but a quick check of its qvector.h does not show
any relevant changes. 
Using std::vector is not an option as I'm actually having this problem with
QPolygonF, a QVector<QPointF> subclass.

Thanks in advance!
Greets,


	Ben




More information about the Qt-interest-old mailing list