Qt Forum

    • Login
    • Search
    • Categories
    • Recent
    • Tags
    • Popular
    • Users
    • Groups
    • Search
    • Unsolved

    Forum Updated on Feb 6th

    [Solved] Am I misusing QPointer?

    General and Desktop
    2
    3
    971
    Loading More Posts
    • Oldest to Newest
    • Newest to Oldest
    • Most Votes
    Reply
    • Reply as topic
    Log in to reply
    This topic has been deleted. Only users with topic management privileges can see it.
    • A
      Asperamanca last edited by

      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)

      1 Reply Last reply Reply Quote 0
      • A
        Asperamanca last edited by

        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.

        1 Reply Last reply Reply Quote 0
        • M
          mmoll last edited by

          [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.

          1 Reply Last reply Reply Quote 0
          • First post
            Last post