qDeleteAll 之后必须清空容器
【1】qDeleteAll应用示例
qDeleteAll源码如下:
1 template <typename ForwardIterator> 2 Q_OUTOFLINE_TEMPLATE void qDeleteAll(ForwardIterator begin, ForwardIterator end) 3 { 4 while (begin != end) 5 { 6 delete *begin; 7 ++begin; 8 } 9 } 10 11 template <typename Container> 12 inline void qDeleteAll(const Container &c) 13 { 14 qDeleteAll(c.begin(), c.end()); 15 }
示例代码如下:
1 #include <QMap> 2 #include <QString> 3 #include <QWidget> 4 #include <QDebug> 5 #include <QApplication> 6 7 class PersonInfo 8 { 9 public: 10 PersonInfo(int id = -1, QString name = QString(), QWidget* pWidget = NULL) 11 : m_nId(id) 12 , m_name(name) 13 , m_pWidget(pWidget) 14 {} 15 16 ~PersonInfo() 17 { 18 m_nId = -1; 19 m_name = QString(); 20 if (m_pWidget != NULL) 21 { 22 qDebug() << "delete personInfo :: " << this; 23 delete m_pWidget; 24 m_pWidget = NULL; 25 } 26 } 27 private: 28 int m_nId; 29 QString m_name; 30 QWidget* m_pWidget; 31 }; 32 33 int main(int argc, char *argv[]) 34 { 35 QApplication a(argc, argv); 36 37 QMap<int, PersonInfo *> map; 38 for (int i = 0; i < 10; ++i) 39 { 40 PersonInfo *pTemp = new PersonInfo(i + 1, QString("hello World!"), (new QWidget())); 41 qDebug() << "construct personInf :: " << pTemp; 42 map.insert(i, pTemp); 43 } 44 45 qDeleteAll(map); // 1.释放内存 46 qDebug() << "after qDeleteAll size :: " << map.size() << endl; 47 map.clear(); // 2.必须清空 48 qDeleteAll(map); // 3.再次释放内存 49 50 return a.exec(); 51 }
打印结果如下:
1 construct personInf :: 0x3bdc20 2 construct personInf :: 0x3c0308 3 construct personInf :: 0x3bfe08 4 construct personInf :: 0x3c0a88 5 construct personInf :: 0x3c1248 6 construct personInf :: 0x3c1738 7 construct personInf :: 0x3c1bb8 8 construct personInf :: 0x3c2420 9 construct personInf :: 0x3c26d0 10 construct personInf :: 0x3c2c68 11 delete personInfo :: 0x3bdc20 12 delete personInfo :: 0x3c0308 13 delete personInfo :: 0x3bfe08 14 delete personInfo :: 0x3c0a88 15 delete personInfo :: 0x3c1248 16 delete personInfo :: 0x3c1738 17 delete personInfo :: 0x3c1bb8 18 delete personInfo :: 0x3c2420 19 delete personInfo :: 0x3c26d0 20 delete personInfo :: 0x3c2c68 21 after qDeleteAll size :: 10
尤其注意打印结果。
可以尝试把2.清空容器行注释掉,然后再运行程序,查看运行结果。
【2】总结
qDeleteAll只负责释放容器元素内存,但没有对容器的置空操作。若无意间二次再执行qDeleteAll过程,程序必会崩溃。
为了避免可恶的崩溃,切记qDeleteAll之后必须清空容器。
Good Good Study, Day Day Up.
顺序 选择 循环 总结