QList size() returns int but QList can store infinite amount of items



  • Hi,

    I have a fundamental question. If QList container can virtually store an infinite number of items, why does the size() and count() functions return an integer ? Shouldn't it support a larger data type than that ? And even if size() and count() are returning larger data types what happens when the actual number of items stored in the qlist exceeds the size of that larger data type - what gets reported as the size or count then ?

    My usecase is to use the QList container for a very large data store and am unsure if the number of items will get correctly reported as the list size.

    thanks,
    Seed


  • Moderators

    I think that if you exceed the maximum, QList will assert and your application will crash - same as it does when you call QList::at() with invalid index.

    If you need bigger containers, use STL or create your own.

    Qt containers use signed integers just to be able to return -1 for errors.



  • The range of a signed integer would allow up to 2.1 billion entries. Using an unsigned integer would allow you to double this but it isn't necessary. For example, using a signed integer, if each entry in QList has even a small amount of data (one 32 bit pointer for data, one for itself, 8 bytes) then you would require a minimum of 17 Gb of memory to hold it all. There is a limit but it is not from the size of the integer used. The disadvantage of using an unsigned integer in this case is obvious, how do you indicated an index error with an unsigned integer (cannot use -1 for this).

    There are cases where a larger integer is needed and there are data types suitable for this (qint64 for example). This is separate.

    I have noticed this myself by the way. The STL versions use unsigned int for .size() where the Qt version uses signed int for the same function. I think the STL version is technically correct but I appreciate not requiring a mix of integer types, complicating things and causing subtle errors if your not careful.

    I read a book that had a section talking about this exact thing. The slant was toward a common type (signed int) and the advantages of this over using an unsigned version. The arguments for a common type made sense to me; I follow this philosophy in everything I write. I think the designers of Qt may have read the same book (or maybe they wrote it). I don't remember the name.


  • Moderators

    Discussion about containers occasionally springs up on Qt mailing lists (where Qt develppers live). Here is a link to most recent one: "link":https://www.mail-archive.com/interest@qt-project.org/msg14436.html.

    There also was a similar and very related discussion about QString a few days ago.


Log in to reply
 

Looks like your connection to Qt Forum was lost, please wait while we try to reconnect.