Usage of QSharedPointer and QVector. Problem with references.
-
Hi all.
I have a problem with QSharedPointer and QVector in this lines of my code:
For example:
@
int tokenCount;
m_vEtoken = QSharedPointer<QVector<QSharedPointer<GeTokenItem> > >(new QVector<QSharedPointer<GeTokenItem> >());
tokenCount = m_Library->GetTokenCount(); // returns 2
m_ListModel = QSharedPointer<QStandardItemModel>(new QStandardItemModel(tokenCount,0,this));
for (int i = 0; i!=tokenCount; i++)
{
m_eToken = QSharedPointer<eToken>(new eToken(m_Library->GetFunctionList(),m_Library->m_slots[i]));
m_eItem = QSharedPointer<GeTokenItem>(new GeTokenItem(m_eToken));
m_eItem->setEditable(false);
m_vEtoken->push_back(m_eItem);
m_ListModel->setItem(i,0,m_eItem.data());
}
@If tokencount == 2. On programm exit i have 2 destructor calls for GeTokenItem and one more that invokes acces violation.
The same is for tokencount == 1.I know that QVector is calling destructors for it's objects, that he is holding. But what can i do in this situation?
Thanks for your time. -
Do you have a working, minimal program that shows the behavior you are seeing? This snippet does not really help in understanding it.
QSharedPointer is not a magic bullet. In general QSharedPointer is useful when you need to have several objects share ownership of something. It is not useful when you have just one owner of the object pointed to. Please do not just replace pointers with QSharedPointers!
E.g. m_ListModel is cleaned up already by its parent (which effectively ownes the model), so using a shared pointer is not advisable there.