qtqscopedpointer

QScopedPointer vs parent


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?


Solution

  • This is completely safe. Here is what happens when an instance of MyClass gets destroyed:

    1. MyClass's destructor gets called (which does nothing in your example)
    2. all member variables of MyClass get destructed. In your case, QScopedPointer's destructor gets called, which means that the child QObject is deleted. When a QObject is destroyed it is removed from its parent's list of children, so the parent no longer tries to delete this QObject
    3. QObject's destructor for your MyClass instance gets called and it sees no children to delete

    You may also want to consider holding your child member QObject by value if there is no reason to allocate it dynamically