Best way to implement the MyModel::mimeData() method without causing a memory leak?
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
Code:
QMimeData* MyModel
::mimeData(const QModelIndexList
&indexes
) const {
}
then it is not clear, who should free the allocated memory.
The original implementation of QAbstractItemModel also allocates new memory without dealocating it :
Code:
{
if (indexes.count() <= 0)
return 0;
if (types.isEmpty())
return 0;
encodeData(indexes, stream);
data->setData(format, encoded);
return data;
}
Does anybody already encountered a problem or have any suggestions?
Thanx in advance!
Re: Best way to implement the MyModel::mimeData() method without causing a memory lea
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,
_
Re: Best way to implement the MyModel::mimeData() method without causing a memory lea
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.
Re: Best way to implement the MyModel::mimeData() method without causing a memory lea
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,
_