PDA

View Full Version : Best way to implement the MyModel::mimeData() method without causing a memory leak?



Yevgen
6th March 2014, 11:01
Hello Qt Community,

I'm wondering, what is the best way to implement the mimeData() method in my custom model class (inheriting QAbstractItemModel) without causing a memory leak.
If I write somethink like this


QMimeData* MyModel::mimeData(const QModelIndexList &indexes) const
{
return new QMimeData(some stuff here);
}

then it is not clear, who should free the allocated memory.

The original implementation of QAbstractItemModel also allocates new memory without dealocating it :


QMimeData *QAbstractItemModel::mimeData(const QModelIndexList &indexes) const
{
if (indexes.count() <= 0)
return 0;
QStringList types = mimeTypes();
if (types.isEmpty())
return 0;
QMimeData *data = new QMimeData();
QString format = types.at(0);
QByteArray encoded;
QDataStream stream(&encoded, QIODevice::WriteOnly);
encodeData(indexes, stream);
data->setData(format, encoded);
return data;
}


Does anybody already encountered a problem or have any suggestions?

Thanx in advance!

anda_skoa
6th March 2014, 16:42
The convention of this method, as evident by the base class's implementation, assumes transfer of ownership to the caller.
Any caller not taking care of deleting the now owned object is in error.

If you model is long lived, e.g. lives for the whole duration of the program's existance, then you could theoretically set the model as the QMimeData object's parent.

Cheers,
_

Yevgen
6th March 2014, 17:06
I've tried your proposal before by setting the model as the parent of the new QMimeData object. And I explicitely didn't delete the pointer anywhere in code manually. Surpisingly it resulted in crash, when the application gets closed. So, somebody deletes the pointer. :)

The drawback of the convention with an ownership transfer for me is when the dragged object leaves the application scope and is dropped somewhere else.

Thank you for the answer.

anda_skoa
6th March 2014, 19:54
Well, the object, as in the instance of QMimeData, obviously never leaves the scope of the process.

Of course a shared pointer would be nice but such API changes can't be introduced that easily.

Cheers,
_