I know that this question is probably opinion oriented, but since I am an amateur programmer I want to know whether this is a good practice to clean up the memory.
To clear my objects I use static QVector in which I store the pointers to the objects created and I made a static function called Perfrom_Cleanup which deletes all the objects from the pointers stored in the vector. Here is my code, to get a clearer idea.
Header File
#ifndef AUTOMATIC_CLEANUP_H
#define AUTOMATIC_CLEANUP_H
#include <QObject>
#include <QVector>
#include <QDebug>
class Automatic_Cleanup : public QObject
{
Q_OBJECT
static QVector<Automatic_Cleanup*> m_Objects;
public:
explicit Automatic_Cleanup(QObject *parent = nullptr);
~Automatic_Cleanup();
static void Perfrom_Cleanup();
signals:
public slots:
};
#endif // AUTOMATIC_CLEANUP_H
CPP File
#include "Automatic_Cleanup.h"
QVector<Automatic_Cleanup*> Automatic_Cleanup::m_Objects;
Automatic_Cleanup::Automatic_Cleanup(QObject *parent) : QObject(parent)
{
m_Objects.append(this);
}
Automatic_Cleanup::~Automatic_Cleanup()
{
qDebug()<<"Deleting object "<<this->objectName();
int i = m_Objects.indexOf(this, 0);
if(i<0)
return;
m_Objects.remove(i);
}
void Automatic_Cleanup::Perfrom_Cleanup()
{
// Deleting from last
for(int i=m_Objects.count()-1; i>=0; i--){
Automatic_Cleanup *obj = m_Objects.at(i);
delete obj;
}
}
From my main cpp file I am doing this, to verify
for(int i=0; i<10; i++){
Automatic_Cleanup *obj = new Automatic_Cleanup;
obj->setObjectName(tr("Object %1").arg(i+1));
if(i==4)
delete obj;
}
Automatic_Cleanup::Perfrom_Cleanup();