c++qtqlistqsharedpointer

Function which returns a QList


I have the following classes

class LMJEntity : public QObject
{
    Q_OBJECT
    Q_PROPERTY(int Id READ getId WRITE setId)
};

class LMJDataMapper : public QObject
{
    Q_OBJECT

    virtual QList<LMJEntity *> *findAll(LMJPaging *paging){
        QList<LMJEntity *> * result = NULL;
        QSqlQuery query;    
        bool ret;       
        ret = query.exec(sql);

        if(!ret){
            errors = query.lastError().text();      
        }else
        {
           result = new QList<LMJEntity *>();
           while(query.next()){
                result->append(load(query));
            }
        }

        return result;
    }
};

Is this a correct way to use QList? Should I use QSharedPointer instead of raw pointer to avoid memory leak? Please give me some suggestions.


Solution

  • There is no point using QSharedPointer inside the QList if the QList instance itself is a normal pointer. Once you loose the pointer to QList, you loose all the memory allocated by shared pointers inside the list.

    It is not necessary to pass QList and all the Qt container-classes including QString by pointers. They use shared-pointers internally, so passing a QList is from the performance perspective more or less the same as passing QList* (see http://doc.qt.io/qt-5/implicit-sharing.html).

    Whether using QSharedPointers for wrapping LMJEntity is a matter of concrete usage. In any case, it won't harm. Your LMJEntity class is derived from QObject. QObjects are deleted automatically with their parents. So if you provide a parent to your LMJEntity instances, than they needn't be shared pointers.

    If not, they will be children of the application, and never be deleted. More than that, they will never be detected as memory leaks by any memleak-checking software.