Question

I currently have a Qt form class called `foo' derived from QMainWindow.

Now in some other class I have something like this

class someclass
{
   private:
      foo* form;
   ......
   public:
      someclass()
      {
          form = NULL; 
      }    
};

Now there is a method in someclass that needs to know if foo* is valid if it is pointing to a valid foo form. I wanted to know what was the best way of achieving this. Should I go with

if(form!=NULL) {...}

The problem is that the above method does not gurantee a reliable valid form . Any suggestions ?

Was it helpful?

Solution

I think you are looking for smart pointers. Usually, this check is done by a weak pointer. This would not hold the ownership for the object, but it could check for the validity with the isNull() method.

Qt has a convenient class established for this, called QWeakPointer. It is usually used in pair with shared pointers, which would be QSharedPointer in the Qt world.

The QWeakPointer class holds a weak reference to a shared pointer

The QWeakPointer is an automatic weak reference to a pointer in C++. It cannot be used to dereference the pointer directly, but it can be used to verify if the pointer has been deleted or not in another context.

QWeakPointer objects can only be created by assignment from a QSharedPointer.

Here goes the method you could actually use to see if the main QSharedPointer owning the object has deleted the referenced pointer.

bool QWeakPointer::isNull() const

Returns true if this object is holding a reference to a null pointer.

Note that, due to the nature of weak references, the pointer that QWeakPointer references can become null at any moment, so the value returned from this function can change from false to true from one call to the next.

This way, the other class would not need to get a reference to the pointer with ownership, but depending on your exact use case, you could just go for QSharedPointer everywhere.

OTHER TIPS

Use QScopedPointer or QSharedPointer depending on the scope of foo class instead of foo*. That would allow reliably check if pointer is valid, comparing pointer to null won't help to detect deleted pointer pointing into the wild.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top