Search code examples
c++qtqlist

Qt: Storing a custom object in a collection by value


Let's say I have this class:

class Bear
{
public:
    Bear ();
    Bear (Bear &other);

    // ... methods

private:
    BearInfo* m_pInfo;
};

Can I store Bear objects in a QList<Bear> by value? According to the documentation:

Internally, QList<T> is represented as an array of pointers to items of type T. If T is itself a pointer type or a basic type that is no larger than a pointer, or if T is one of Qt's shared classes, then QList<T> stores the items directly in the pointer array.

While my class just consists of a pointer, it is neither a pointer type nor a basic type, so it seems to me that the QList will store pointers (Bear*), which is not what I want. And since the BearInfo structure must be mutable, I cannot derive Bear from QSharedDataPointer.

Any suggestions how I can enable this class to be stored by value in the Qt collections?


Solution

  • Use a QVector, the Qt Documentation states this:

    QList, QLinkedList, and QVarLengthArray provide similar functionality. Here's an overview:

    • For most purposes, QList is the right class to use. Operations like prepend() and insert() are usually faster than with QVector because of the way QList stores its items in memory (see Algorithmic Complexity for details), and its index-based API is more convenient than QLinkedList's iterator-based API. It also expands to less code in your executable.
    • If you need a real linked list, with guarantees of constant time insertions in the middle of the list and iterators to items rather than indexes, use QLinkedList.
    • If you want the items to occupy adjacent memory positions, or if your items are larger than a pointer and you want to avoid the overhead of allocating them on the heap individually at insertion time, then use QVector.
    • If you want a low-level variable-size array, QVarLengthArray may be sufficient.