c++qtqsharedpointer

Deleting a QObject that QSharedPointer is pointing to


In my project I create QObject instances and give them a parent-child relationship. I also want to keep track of some of the objects with QSharedPointer instances.

When an object gets deleted, either by delete childObject; or delete parentObject;, I would like the QSharedPointer instances to return true when calling isNull().

However, upon deleting any object QSharedPointer points to, my program crashes.

Here is my code:

QObject *child = new QObject();
QSharedPointer<QObject> ptr(child);
delete child;

This alone crashes my program. I read the documentation for QSharedPointer and it states A QSharedPointer object can be created from a normal pointer so I'm a bit confused as to why QSharedPointer can't handle the object pointed to being deleted.

QPointer doesn't have this problem, and I can even call isNull(), however the reason I need QSharedPointer is because some child objects will be created and not given a parent, at which point I want the child object to be deleted when all relevant QSharedPointers go out of scope.


Solution

  • The QSharedPointer takes ownership of the raw pointer that you pass to it. That means once all shared pointers go out of scope it will delete the object it points to. If you already manually delete an object then that will lead to a double free which causes a crash (if you are lucky!).

    With a shared pointer you don't have to manually call delete at all as that will happen automatically as mentioned above.