Important: Please read the Qt Code of Conduct - https://forum.qt.io/topic/113070/qt-code-of-conduct

Deleting QObjects in QMap



  • I defined a struct like this:

    struct MyStruct
    {
        MyClass1 *class1;
        MyClass2 *class2;
    };
    

    Both classes inherits QObject. Then I have:

    QMap<int, MyStruct> map;
    
    // ...
    MyStruct s;
    s.class1 = new MyClass1();
    s.class2 = new MyClass2();
    map.insert(1, s);
    

    Now I want to remove an item from map:

    map.remove(1);
    

    What is the right way to clean up the objects?

    1. I don't need to explicitly do it because QObject are automatically destroyed when parent dies (map item?)
    2. I have to call delete map[1].class1; delete map[1].class2
    3. ...

  • Lifetime Qt Champion

    Hi,

    QMao is neither a QObject nor a parent of your MyStruct objects. It's a container.

    You should add a destructor to your structure that will delete its members or use solution number 2.



  • @SGaist said in Deleting QObjects in QMap:

    You should add a destructor to your structure that will delete its members or use solution number 2.

    The destructor will be automatically called when I remove the item from the map or I still have to manually call it?


  • Lifetime Qt Champion

    The destructor is called when the object is deleted. You usually never call a destructor by hand.



  • @SGaist said in Deleting QObjects in QMap:

    The destructor is called when the object is deleted. You usually never call a destructor by hand.

    Ok, I understand this. But the question was if Qt delete the object when I remove the item from the map. Example:

    map.remove(1);
    

    if the struct has the destructor, is it called during remove()? Otherwise I still have to: delete map[1]; before remove it.


  • Lifetime Qt Champion

    remove deletes the object.

    Note that writing a quick test would have gotten you the answer faster.



  • @SGaist said in Deleting QObjects in QMap:

    remove deletes the object.

    Ok.

    Note that writing a quick test would have gotten you the answer faster.

    Well, I'm actually running a test, but I still don't understand some behaviors. So I asked to be sure at least on something...


  • Lifetime Qt Champion

    @Mark81
    Hi
    Well you want to do like

    struct MyStruct {
        MyClass1 *class1 = nullptr;
        MyClass2 *class2 = nullptr;
        ~MyStruct()
        {
            delete class1;
            delete class2;
        }
    };
    

    The reason this works is that you have
    QMap<int, MyStruct> map;
    so when you call remove its actually deleted as its inline instance and not a pointer.
    Had you
    QMap<int, MyStruct *> map;

    remove would only delete the pointer from the map but not called
    MyStruct destructor.


Log in to reply