[Qt-interest] Iterators and implicitly shared containers
Scott Aron Bloom
Scott.Bloom at onshorecs.com
Fri Dec 17 22:37:43 CET 2010
-----Original Message-----
From: qt-interest-bounces+scott.bloom=onshorecs.com at qt.nokia.com
[mailto:qt-interest-bounces+scott.bloom=onshorecs.com at qt.nokia.com] On
Behalf Of Sean Harmer
Sent: Friday, December 17, 2010 12:52 PM
To: qt-interest at qt.nokia.com
Subject: Re: [Qt-interest] Iterators and implicitly shared containers
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
_______________________________________________
Yes... however, the *it=2; should recognize that the ref count > 1, and
do a detach/deep copy as necessary no??
Soctt
More information about the Qt-interest-old
mailing list