We would like to combine the benefits of a smart pointer, we don't care which one(s), and parented QObjects with lifespans shorter than their parents. Specifically, if a parent QObject has a member smart pointer to a child, and that child may get destroyed and recreated several times through the parent's existence. It would be great to use a smart pointer for the child, as a developer wouldn't leak memory accidentally - at least for the duration of the life of the parent - if they failed to check the member's existence before creating a new instance.
We run into an issue with smart pointers (specifically std::shared_ptr) during the Parent's destruction. This can lead to a segfault. We suspect that the child is destroyed by its parent because it is owned by the parent and then when the shared_ptr goes out of scope destruction tries to happen again, although the order of this is somewhat suspect to us. We would think that the shared_ptr would go out of scope first as the Parent's destructor is called, which would in turn call delete on the owned object and then the base class QObject's destructor would be called, which would try and delete the Child (who it isn't aware was deleted by the shared_ptr, for some reason). Some searching of various forums indicates that smart pointers shouldn't be mixed with parented objects for this reason.
Here's a crash stack trace for a parented QTimer that was wrapped in a smart pointer.
crashlog.20160223-141028.3295:*** SIGSEGV (@0x7f4d4c4afbb8) received by PID 3295 (TID 0x7f4d823d8a80) from PID 1279982520; stack trace: ***
crashlog.20160223-141028.3295- @ 0x7f4d793b6d40 (unknown)
crashlog.20160223
-141028.3295- @ 0x7f4d7a9d395f
QObject::killTimer()crashlog.20160223
-141028.3295- @ 0x7f4d7a9d8e01
QTimer::stop()crashlog.20160223
-141028.3295- @ 0x7f4d7a9d8e91
QTimer::~
QTimer()crashlog.20160223-141028.3295- @ 0x7f4d80f787c9 std::shared_ptr<>::~shared_ptr()
crashlog.20160223-141028.3295:*** SIGSEGV (@0x7f4d4c4afbb8) received by PID 3295 (TID 0x7f4d823d8a80) from PID 1279982520; stack trace: ***
crashlog.20160223-141028.3295- @ 0x7f4d793b6d40 (unknown)
crashlog.20160223-141028.3295- @ 0x7f4d7a9d395f QObject::killTimer()
crashlog.20160223-141028.3295- @ 0x7f4d7a9d8e01 QTimer::stop()
crashlog.20160223-141028.3295- @ 0x7f4d7a9d8e91 QTimer::~QTimer()
crashlog.20160223-141028.3295- @ 0x7f4d80f787c9 std::shared_ptr<>::~shared_ptr()
To copy to clipboard, switch view to plain text mode
Regardless of our understanding of the crash, we would prefer to know the correct usage (if any) for mixing smart pointers and parented QObjects. We realize that in many cases parenting a QObject is unnecessary if a smart pointer is used, such as the above QTimer, but there are examples when the Qt parenting scheme is quite useful such as UI elements.
Bookmarks