[Interest] Help, please !!!

Nikos Chantziaras realnc at gmail.com
Thu Apr 26 18:47:39 CEST 2012


On 26/04/12 19:01, André Somers wrote:
> Op 23-4-2012 20:44, Nikos Chantziaras schreef:
>> Then you're not doing what you think you're doing:
>>
>>       QList<  QList<int>  >  listOfLists;
>>       QList<int>  listOfInts;
>>       listOfInts.append(10);
>>
>>       listOfLists.append(listOfInts);
>>       listOfLists[0][0] = 9;
>>
>>       qDebug()<<  listOfLists[0][0]<<  listOfInts[0];
>>
>> You are modifying a copy, so it prints"9 10"  instead of"10 10".  This:
>>
>>     listOfLists[0][0] = 9;
>>
>> modifies a copy of listOfInts.  Also the reverse is true.  If you modify
>> listOfInts, then the copy of it inside listOfLists is not updated.
>>
>> "Implicit sharing"  means that data is copied when it's modified.  It's
>> not a replacement for pointers.
>>
> Not true, in this case.

I posted code that proves my point.  It prints "9 10".  You can't argue 
with that one ;-)


> Let's look at the signature of the operator that
> Scott is using:
> T & QList<T>::operator[](int i);
>
> Note the little & after the first T? That's right, it returns a
> *reference*. And a reference is something you can directly modify. The
> documentation for that method also explicitly states that:
>
>  > Returns the item at index position/i/as a *modifiable* reference.
>
> Your statement that "implicit sharing" means that a copy is made when
> data is modified, is way too general. That is only true if you actually
> *have* a (shared) copy (which you don't in this case).

Yes, it returns a reference to the copy.  It doesn't return a reference 
to the original.  References in cases like this are used for 
optimization purposes, so that less copying is involved.

Bottom line is, it's still a copy.  Without a pointer, there's no way to 
modify the original.  And if you think your code is correct by having 
this wrong assumption, you're in for buggy surprises.




More information about the Interest mailing list