Is this the corrected way to use QPointer?

2.3k views Asked by At

How could I check whether a pointer's content is deleted? If I use QPointer like this:

myClass::myClass(myStruct* p){
 _p = p;//_p is a QPointer<myStruct>
}

myClass::function(){
if(_p) {_p->function();}
}

then I have

myStruct* p = new myStruct();
myClass A(p);
delete p;
A.function();

will the last A.function() cuase the _p->function() be called and therefore cause access violation? when I delete p, what will happen to _p?

1

There are 1 answers

3
hyde On BEST ANSWER

If myStruct is a QObject subclass, then your code should work, as much as can be said from shown snippets. The QObject destructor will clear every QPointer pointing to the destructed instance. If it isn't a QObject subclass, then you should get compile/link error.

Quote from the docs:

Note that class T must inherit QObject, or a compilation or link error will result.