autodelete pointer QList
-
Hi,
in old QT3 we had QPtrList which was able to delete automatically (method: setAutoDelete) objects after the pointer was removed from list (https://linux.die.net/man/3/qptrlist). What would a good option to get this done with a QList (from Qt5/6)?
Should I override QList or could I get this done more directly?Thank you!
-
Hi,
Check qDeleteAll.
-
@SGaist is on the money if you want to delete everything in the list.
If you want only single items to be deleted when removed from a list of bare pointers then
QList<T*> list; ... delete list.takeAt(1);
is about as simple as it gets.
To avoid direct delete smart pointers might work for you:
#include <QCoreApplication> #include <QList> #include <QDebug> #include <memory> class Blah { public: Blah(int i): m_num(i) { qDebug() << m_num << "Blah()" << this; } ~Blah() { qDebug() << m_num << "~Blah()" << this; } private: int m_num; }; int main(int argc, char *argv[]) { QCoreApplication a(argc, argv); QList<std::shared_ptr<Blah> > list; list.append(std::make_shared<Blah>(0)); list.append(std::make_shared<Blah>(1)); list.append(std::make_shared<Blah>(2)); list.append(std::make_shared<Blah>(3)); qDebug() << "Before remove"; list.removeAt(1); qDebug() << "After remove"; return 0; }
0 Blah() 0x5584039f4c60 1 Blah() 0x5584039f57a0 2 Blah() 0x5584039f51c0 3 Blah() 0x5584039f5ae0 Before remove 1 ~Blah() 0x5584039f57a0 After remove 3 ~Blah() 0x5584039f5ae0 2 ~Blah() 0x5584039f51c0 0 ~Blah() 0x5584039f4c60
-
@ChrisW67 Thank you! Yes, I thought about smart pointers as well but I am (yet) not very familiar with it and don't know which one is correct. Currently we work most of the time with raw pointers and the old Qt3 QPtrList .
Maybe the qt-version: https://forum.qt.io/topic/19073/any-difference-between-std-shared_ptr-and-qsharedpointer/2 could be an option as well...