I need some explanation about the next situation. Assume we have the next code:
class MyClass : public QObject
{
public:
MyClass(QObject* parent = nullptr)
{
m_member.reset(new QObject(this));
}
~MyClass(){} override;
private:
QScopedPointer< QObject> m_member;
};
I can't understand if it's safe to pass an object with a parent to QScopedPointer. Might it be any situation when the object is deleted twice by the parent and by the smart pointer and it will lead to a crash?
This is completely safe. Here is what happens when an instance of
MyClassgets destroyed:MyClass's destructor gets called (which does nothing in your example)MyClassget destructed. In your case,QScopedPointer's destructor gets called, which means that the childQObjectis deleted. When aQObjectis destroyed it is removed from its parent's list of children, so the parent no longer tries to delete thisQObjectQObject's destructor for yourMyClassinstance gets called and it sees no children to deleteYou may also want to consider holding your child member
QObjectby value if there is no reason to allocate it dynamically