QPointer has a method, clear().

Clears this QPointer object.

I am not sure what "clear" exactly means. In my mind, it could mean

  1. It deletes the pointer you referenced.

or

  1. It un-attaches the pointer you referenced, leaving that pointer on the heap, and the QPointer<T> object no longer tied to any pointer.

Maybe it means something else? Could you please let me know what it actually does?

1

There are 1 answers

0
Kuba hasn't forgotten Monica On BEST ANSWER

QPointer is a tracking pointer. It tracks the lifetime of an object. It doesn't do any owning duties. It never will deallocate any storage owned by QObject. It can deallocate the underlying implementation detail - the shared reference object, but that doesn't affect anything really that the user cares about; those objects are deallocated only when the underlying QObject is gone and the last QPointer is being destructed.

It deletes the pointer you referenced.

That's IMHO a rather confusing language. Pointers are values. To reference a pointer has a well established meaning:

const int *q = ....; // a pointer
*q; // a pointer dereference (not used for anything)

To me, "deleting a pointer" is this:

// dynamically allocate a pointer
int **p = new int*();
// make it point somewhere
int i = {};
assert(0 == i);
*p = &i;
// use it
**p = 44;
assert(44 == i);
// delete it
delete p; // a pointer-to-integer got deleted

It un-attaches the pointer you referenced, leaving that pointer on the heap, and the QPointer<T> object no longer tied to any pointer.

It's pointers galore for sure, but that's veritable goobledygook. Just because I might understand what you mean doesn't imply that anyone should talk that way :)

A QPointer<T> tracks the lifetime of a T-instance, an object. It's objects it tracks, not pointers. So clear() makes the QPointer not track whatever object of type T it was tracking. That's all. And that's how to say it without making everyone doubt their sanity :)

It is true that the way you make a QPointer track an object is by pointing to it via a raw pointer. That's just how you get a QPointer going, that's all.

It is incorrect to conflate QPointer with heap - no heap is involved in the example below, at least not explicitly. The obj instance is an automatic variable. Implementations are free to put it on the dynamic store of some kind - even a literal heap, but that's typical of C++ interpreters and not what we're usually used to :)

#include <QtCore>
int main() {
  QPointer<QObject> p;
  Q_ASSERT(p.isNull());
  {
    QObject obj;
    p = &obj;
    Q_ASSERT(!p.isNull());
  }
  Q_ASSERT(p.isNull());
}