[Interest] QList operator[]

K. Frank kfrank29.c at gmail.com
Sat Jan 10 18:19:26 CET 2015


Hello Brad!

Something also seems fishy to me here.  I would like to understand
it better.

On Fri, Jan 9, 2015 at 4:07 PM, Brad Pepers <bpepers at me.com> wrote:
> Ah I see...  So it's the const-ness of the object itself and not the
> reference that is controlling which operator[] gets used.  That makes sense
> to me now.
>
> I'm still not sure what is happening with all that memory though.  I'm
> asking for a reference so I don't expect that I own what is returned yet it
> seems to be making a deep copy each time and not freeing that memory since
> in seconds the memory use of the process sky-rockets until the whole system
> starts thrashing and eventually crashes and burns.

Regardless of non-const operator[] triggering a deep copy, I still don't
understand where the memory leak should be coming from.  I think I
may have a C++ misunderstanding rather than a QList issue.

Suppose I have:

   std::vector<MyClass> someBigVector;

   for (unsigned i = 0; i < someBigNumber; i++) {
      std::vector<MyClass> tempVector {someBigVector};
      tempVector[17] = MyClass {1, 2, 3};

   }

tempVector is indeed a copy (by value) of someBigVector, and takes
up space.  But tempVector is in scope local to the for-loop, so when it
goes out of scope at the end of each iteration of the loop it should be
destroyed and its memory released.

So while the copy of tempVector might be inefficient and not what we
want, it shouldn't be a memory leak and cause memory usage to grow
as the loop keeps iterating.

Am I missing something on the C++ side, or is there something I don't
understand going on under the hood of QList that leads to Brad's
memory leak?

> Seems odd behaviour to
> get from a couple of lines of code like that.  Would never have expected
> that to be a memory leak!

I agree that something odd is going on here.  I understand why you
got a deep copy that you didn't anticipate, but I don't see why that
would lead to a memory leak.

I'm hoping that the experts can shed some more light on this issue.

> Makes me wonder if I've done the same kind of
> mistake in other places where it's not so noticeable...
>
> Brad


Best.


K. Frank


> On Jan 09, 2015, at 01:21 PM, Keith Gardner <kreios4004 at gmail.com> wrote:
>
>> QList can return a const & with the [] operator [1]. The documantation
>> even says it's the same as .at().
>>
>> [1] http://doc.qt.io/qt-5/qlist.html#operator-5b-5d-2
>>
> That is true if the QList is const when calling the function.  If it is not,
> the other operator [1] documentation describes the behavior.
>
> [1] http://doc.qt.io/qt-5/qlist.html#operator-5b-5d
> ...



More information about the Interest mailing list