Important: Please read the Qt Code of Conduct - https://forum.qt.io/topic/113070/qt-code-of-conduct

Clearing a QSharedPointer pointed by QSharedPointer and QWeakPointer.



  • In the following code,

    int *pI = new int(9);//memory allocated
    QSharedPointer<int> pI1(pI);//shared pointer pointing to pI
    QWeakPointer<int> pI2 = pI1;//weak pointer pointing to pI
    pI1.clear();
    
    qDebug()<<*pI; //prints 9 - no segmentation fault
    
    qDebug()<<pI2.isNull(); // evaluates to true
    qDebug()<<pI1.isNull(); //evaluates to true
    

    why I am able to dereference *pI.Won't shared pointer delete it from heap after pI1.clear()?


  • Moderators

    It may be deleted, but the data is still there. You're accessing "dead" memory.


Log in to reply