Please nominate your Qt Champions for 2021!

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));

    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.

  • Moderators

    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.

  • Thanks Tobias.

    Adding this to destructor helps:


    I'am reading book about smart pointers and getting started with QT. Next i will be more attentive to this.

Log in to reply