[Solved] Am I misusing QPointer?



  • I have a class (MyItem) that can point to a QObject-derived class (MyGroup). In MyItem's destructor, I need to notify MyGroup. However, MyGroup might have been destroyed previously.

    So I check the validity of the object by creating a QPointer to MyGroup:

    @QPointer<MyGroup> pGuardedGroup(m_pMyGroup);@

    However, I get an Access Violation on this line if m_pMyGroup is invalid (already destructed) at this point.
    Wasn't QPointer intended for such a use case?

    (Windows 7 + Qt 4.8.2)



  • Answering my own thread:
    It seems that a QPointer must already exist in order to be set to NULL when the object goes out of scope. Thinking about it, how could a QPointer make sense out of something that is left over in the garbage space of memory (or worse still, recycling space).

    Somehow I had hoped that QPointer would check whether what it finds in memory conforms to the type and kind of object it expects, but even that would not be safe if the memory is re-used by the same object type.



  • [quote author="Asperamanca" date="1392798060"]Am I misusing QPointer?[/quote]
    Yes, you are.

    [quote author="Asperamanca" date="1392798060"]
    So I check the validity of the object by creating a QPointer to MyGroup:

    @QPointer<MyGroup> pGuardedGroup(m_pMyGroup);@

    However, I get an Access Violation on this line if m_pMyGroup is invalid (already destructed) at this point.
    Wasn't QPointer intended for such a use case?
    [/quote]

    No. What QPointer does is to register connections with the QObject it points to so that it is notified when the object is destroyed. It cannot set up these connections if the pointer it is initialized with does not even point to a valid object. The solution involves making m_pMyGroup a QPointer.


Log in to reply
 

Looks like your connection to Qt Forum was lost, please wait while we try to reconnect.