[Qt-interest] Iterators and implicitly shared containers

Sean Harmer sean.harmer at maps-technology.com
Fri Dec 17 21:51:43 CET 2010


On 17/12/2010 18:22, Ben Swerts wrote:
> 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

Call v2.detach(). Look at the source for QVector and friends and you;ll 
see this is a public inline function. Alternatively just call any 
non-const function on v2 to trigger a deep copy.

HTH,

Sean



More information about the Qt-interest-old mailing list