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