QList children - struct or custom classes derived from QObject?
Question
I'm currently working on Qt application on Symbian platform. Application has an sqlite database and initial data is populated from txt files.
I'm implementing online update from data that comes in json format. So i would like to create generic functions in my db update class that takes QList
of classes/structs and updated db from them. QList
would be populated with objects either from txt, or json.
I already have the parsing in place, just considering what would be better in terms for performance:
- Creating c++ structs and passing them (as objects hold only simple data) wrapped in
QList
- Creating custom classes derived from
QObject
and passing them as pointers inQList
and then deleting everything withqDeleteAll
- Any other way...
Solution
That depends on whether your classes are carrying behaviour or only state.
They carry behaviour.
Then, a polymorphic class is in order, yes. Whether it needs to inherit from
QObject
is another question. Inherit fromQObject
only if you need its services (introspection, signals/slots, event handling). Otherwise, don't.As for
qDeleteAll()
: I wouldn't go there. Instead of naked pointers, use smart pointers, e.g.QSharedPointer
. They keep track of the number of references to their payload, deleting it when the refcount falls to zero.In this case, don't use
QList
, but a more efficient container such asQVector
.They carry only state.
Then, a "dumb"
struct
may suffice. In this case, don't useQList
as a container, but something more efficient, likeQVector
(don't forget to make good use of thereserve()
method).
In general, try to avoid QList<T>
for types T
where sizeof(T)>sizeof(void*)
and non-buildin/non-Qt-types, because QList
performance is degraded for these.