0

Hello and good morning together, I have two questions concerning QVector and its usage. I have an own custom class. It is necessary to use QVector<QSharedPointer<Class*>> or does it suffice to directly add instances to QVector like QVector<Class*>>. I read that QVector already uses a shared pointer internally contrary std vector. It is bad practice to append instance pointer directly?

Next, I want to have a subset of QVector with selected elements. What is good practice to do that using QVector>?

 __________
|QVector   |
|   _______|
|  |QVector|
|__|_______|
Findus
  • 303
  • 1
  • 4
  • 17
  • 1
    If you put pointers into a vector, the objects pointed to are not managed by QVector (or any other Qt or STL container) and you need to manage them manually. So if you want shared_ptr behavior, you need to use QVector>. Assuming you need pointers at all, and Class can't be used per value. (The second part I don't fully understand but you probably want a QVector>>) – Frank Osterfeld Mar 17 '20 at 07:56
  • Thank you, Frank. I edited my post. Do you think append pointers directly to QVector is bad practice? And manging the instance manually? – Findus Mar 17 '20 at 08:29
  • 1
    I think it's ok if you take some precautions, like keeping the vector encapsulated in a class with only a few places where items are removed (and thus deleted), and not pass around copies of the vector where the ownership of the items then might be unclear. – Frank Osterfeld Mar 17 '20 at 08:40

1 Answers1

0

Mayble it's not gut idea to use QVector to directly add instances. Better solution is using QList container.

It does not store objects directly, but instead stores pointers to them. You gain all the benefits of quick insertions at both ends, and reallocations involve shuffling pointers instead of copy constructors, but lose the spacial locality of an actual or , and gain a lot of heap allocations.

QList<QList<Class>> testlist, and don't forget to override operator =