Enhancing QList

  • I have a large and unwieldy set of customised container classes which I want to simplify and rationalise using standard container classes. Having looked through the documentation for the various STL and Qt container types, it looks as though QList does almost everything I need. There are in fact just two things I need which aren't provided (at least as far as I can see):

    • The documentation says "Internally, QList<T> is represented as an array of pointers to items of type T". That being the case, I'd expect there to be a
      @T** QList::data()@

    function but there does not seem to be one.

    • My types 'T' are very large image files which can be megabytes in size; I want to ensure that they are copied as infrequently as possible, so I'd like to be able to move objects into the list instead of having to copy them. In other words, it would be great if there were methods along the lines of:
      @void QList::append(T && value);
      void QList::insert(int i, T && value);@

    but there don't seem to be such things, although on the face it they should be very straightforward to implement.

    It seems that I can't safely subclass QList because it doesn't have a virtual destructor. As a C++ programmer of middling ability, is hacking the QList source code something I should contemplate, or does anyone reading this know of a better way of approaching the basic requirement?

  • Moderators

    and why don't you just store pointers to your images in the list? (QList<MyImage*>)
    This ensures that the image data isn't copied.

  • Mainly because with QList<T> plus the extra features, I could reproduce the exsiting functionality of my existing custom container in full without needing to refactor the rest of my code base.

  • Moderators

    then implement implicit sharing for your image data. So you can create copies (by value) of your image-wrapper but the internal data (shared pointer) is the same for all.

    for this you need to reimplement the copy-constructor, the assignment operator and probably provide a (optional) clone() method which returns a copy of the data of your image. The internal image data is held by a "QSharedDataPointer":http://doc.qt.io/qt-5/qshareddatapointer.html for example.

  • That actually looks very promising... I'll dig into that a bit more. Thank you.

Log in to reply

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