PDA

View Full Version : how to pass a QList pointer



ehnuh
4th November 2012, 06:47
Hi, I would like to ask how to properly pass a QList to another function? I have researched and discovered that QLists must be passed via pointer.

For example:
I have a qlist of plugins

QList<PluginInterface *> *PluginList;

and declared and instantiated it in this manner PluginList = new QList<PluginInterface *>();



..the function that will receive this list has a function prototype of

void receive_qlist(QList<PluginInterface> *);


..is this method correct and efficient?

Zlatomir
4th November 2012, 08:22
Just pass PluginList to the function is not working? If so tell us the error. One error is the function prototype that receives QList of PluginIntergface objects not pointers, so either use void receive_qlist(QList<PluginInterface*> *); //notice the extra * or declare your QList to hold objects: QList<PluginInterface> *PluginList; - depending on what you really want.

But QList doesn't really need to be allocated on heap, so allocate on heap only if you really need that (and if you go with QList of pointers don't forget to delete all the pointers from QList when before you delete the QList pointer), so you can do just QList<PluginInterface*> pluginList; (now the QList is on the stack - maybe a member into an object that lives as long as that QList is needed)

As for passing the QList as parameter read about implicit sharing of some Qt classes here (http://doc.qt.digia.com/qt/implicit-sharing.html#shared-classes) and decide what you really need to do to the QList in the function so depending on that you can choose to pass a QList& or a const QList& or if you need QList* or just a QList and let the implicit sharing work (read the documentation linked above because there are cases when a deep copy will be made - this might affect performance or the logic of your application - depending on data type that you use in the list)

amleto
5th November 2012, 16:30
Hi, I would like to ask how to properly pass a QList to another function? I have researched and discovered that QLists must be passed via pointer.


wrong. QLists can be passed by value or by reference or via indirection (pointer).

pick your poison:

void func(QList<int> list) // func will use a copy of list
void func(QList<int>& list) // func will use the same instance of list
void func(QList<int> const & list) // func will use the same instance of list and will not* modify it
void func(QList<int>* list) // func will take a pointer to a QList<int> (that may be valid or not...)

PS
This is a general programming question, not a Qt programming question as you are merely asking about c++ syntax