How to delete the objects from QMap?



  • I would like to delete all object from the QMap. I try different ways but destructor is not call. what is wrong am i doing?

    try 1:

    #include <QtCore/QCoreApplication>
    #include "qalgorithms.h"
    
    #include "qdebug.h"
    #pragma pack(push,1)
    
    class absrectClass {
    public:
    	void fun() {
    		qDebug() << "fun is call";
    	}
    	virtual void fun1() = 0;
    protected:
    	int x;
    };
    
    class derived2 : public absrectClass {
    
    public:
    	~derived2() {
    		qDebug() << "delete derived2 object";
    	}
    
    	void fun1() {
    		qDebug() << "fun1 is call from derived2";
    	}
    
    };
    
    int main(int argc, char *argv[])
    {
    	QCoreApplication a(argc, argv);
    	QMap <QString,absrectClass*> mapper;
    	mapper["object1"] = new derived2();
    	mapper["object2"] = new derived2();
    	
    	qDeleteAll(mapper);
    
    

    try 2:

    #include <QtCore/QCoreApplication>
    #include "qalgorithms.h"
    
    #include "qdebug.h"
    #pragma pack(push,1)
    
    class absrectClass {
    public:
    	void fun() {
    		qDebug() << "fun is call";
    	}
    	virtual void fun1() = 0;
    protected:
    	int x;
    };
    
    class derived2 : public absrectClass {
    
    public:
    	~derived2() {
    		qDebug() << "delete derived2 object";
    	}
    
    	void fun1() {
    		qDebug() << "fun1 is call from derived2";
    	}
    
    };
    
    int main(int argc, char *argv[])
    {
    	QCoreApplication a(argc, argv);
    	QMap <QString,absrectClass*> mapper;
    	mapper["object1"] = new derived2();
    	mapper["object2"] = new derived2();
    	
    	foreach(auto it, mapper.values())
    	{
    		delete it;
    	}
    
    	return a.exec();
    }
    
    

    any one please give me direction?


  • Lifetime Qt Champion

    Hi
    You store pointers in the map. So if you call clear() it just deletes the pointers.
    Not the objects they points too.
    You can use
    void qDeleteAll(const Container &c)
    and
    clear() to completely delete all of it.
    http://doc.qt.io/qt-5/qtalgorithms.html#qDeleteAll



  • I get this :

    warning: delete called on 'absrectClass' that is abstract but has non-virtual destructor [-Wdelete-non-virtual-dtor]
            delete it;
            ^
    

    Something's missing in your code :)



  • @mrjj Thank you for response.

    You can see in "try 1" for deleting object I use qDeleteAll(mapper); inside the main function.

    I found mistake, I forgot to make virtual destructor of base class.

    virtual ~absrectClass() {
    	}
    

    Now it is call to derived class destructor .

    Thank you



  • @mpergand Thank you for help.