Better_Software_Header_MobileBetter_Software_Header_Web

Find what you need - explore our website and developer resources

PSA: QPointer has a terrible name

QWidget *w = new QWidget(parent); // create a new object; `parent` owns it

QPointer<QWidget> ptr = obj;      // create a weak pointer, watching over *w
Q_ASSERT(ptr);                    // ptr is valid, *w still exist 

destroyWidget();                  // destroy *w somehow
Q_ASSERT(!ptr);                   // ptr is automatically reset,
                                  //   to signal that *w is gone
class MyClass {
  QPointer<SomeObject> m_resource;  // pointer to some resource we don't own

  void doSomething() {
    if (m_resource)        // check that the resource is still alive;
      m_resource->use();   // if so, use it
  }
};
class MyObject : public QObject {
  Q_OBJECT

signals:
  void aSignal(int value);

public:
  void doSomething() {
    int value = calculateValue();

    QPointer<MyObject> guard(this);
    emit aSignal(value);
    if (!guard)
       return;

    // do some other things
  }
};
WeakPointer<Foo> weakPtr; // declared somewhere

// Here's how one would use it:
if (weakPtr)               // is the object still alive?
  weakPtr->doSomething();  // use it!
std::weak_ptr<Foo> weakPtr; // declared somewhere

// Test and use:
std::shared_ptr<Foo> sharedPtr = weakPtr.lock();
if (sharedPtr)               // sharedPtr, not weakPtr!
  sharedPtr->doSomething();  // object is alive, use it
QPointer<MyQObject> ptr;

if (ptr)               // is the object still alive?
  ptr->doSomething();  // use it!

About KDAB


GiuseppeD'Angelo

Giuseppe D’Angelo

Senior Software Engineer

Learn Modern C++

Learn more