2

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?

demonplus
  • 5,613
  • 12
  • 49
  • 68
Nyaruko
  • 4,329
  • 9
  • 54
  • 105

1 Answers1

2

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.

hyde
  • 60,639
  • 21
  • 115
  • 176
  • But when is the QPointer set back to NULL? once the delete p is called, is it set back to NULL immediately(assume the delete p and the QPointer are in the same thread )? If there's another thread emiting signal to trigger myClass::function(), will the example in my question still be safe? – Nyaruko Dec 12 '14 at 21:14
  • 1
    In C++, with no garbage collection, `delete` will cause the object destructors to be called immediately, in reverse order, so `QObject::~QObject` is the last destructor to be called, but it will be called before `delete` "returns". If you use inter-thread signals, they should be queued, so deleting the object should not be a problem. – hyde Dec 13 '14 at 08:21
  • 1
    @Nyaruko If you call any method of the object being deleted from another thread while it is being deleted (or doing anything else which is not explicitly thread safe), be it direct method call, or via `Qt::DirectConnection` signal, it's basically a bug in your program. – hyde Dec 13 '14 at 08:23