(emphasis is mine)
Then you shouldn't use reference-counted smart pointers such as std::shared_ptr or QSharedPointer, because they precisely allow objects to escape a scope. The parent QObject is already managing the child's lifetime; everyone else can just manipulate a plain Child * pointer without worrying when to delete it (but must still be careful not to access the child after the parent has been destroyed).
I suggest one of those two options:
- store the pointer to the child in a plain Child * private member, and add a helper method void resetChild(Child *newChild) that deletes the existing child, if any (or calls deleteLater(), depending on your needs), before setting the new pointer. Explain to the developers that they must go through this method to set up a new child.
- if that is not enough (i.e. some developers keep modifying the Child * member directly), wrap the Child * in a smart pointer that forces updates to go through the method. std::unique_ptr (or QScopedPointer) do the trick, except that the parent's destructor must take care of calling unique_ptr::release() (or QScopedPointer::take()) to avoid double deletion. Or just implement a minimal ad hoc smart pointer yourself, which only initializes the Child * to NULL and forces updates to delete the existing child first.
Bookmarks