1

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.

mrg95
  • 2,371
  • 11
  • 46
  • 89

1 Answers1

1

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.

Stephan Dollberg
  • 32,985
  • 16
  • 81
  • 107
  • Thanks. However when I call delete on the parent object, the children also get deleted. This is the crux of my problem. It seems I can't let the parents and QSharedPointer both handle the children right? – mrg95 Oct 20 '18 at 22:13
  • 1
    @mrg95 You need to decide which way of managing resources to choose. If you want to go the shared pointer way then just don't give the children objects any parent. – Stephan Dollberg Oct 20 '18 at 22:14
  • Do you think there is any way to detect and prevent QSharedPointer from doing that second delete? Subclass perhaps? – mrg95 Oct 20 '18 at 22:16
  • @mrg95 No, the whole point of QSharedPointer is to do exactly that once all instances go out of scope. – Stephan Dollberg Oct 20 '18 at 22:18
  • Okay sounds like I'll have to store the child objects in a QVector or something inside the parent objects... Thanks for the help! :) – mrg95 Oct 20 '18 at 22:20