Qt 清空QHash表中new出来的对象

释放分两种情况(QHash<Key, T>):

   1.T的类型为非指针,这时候直接调用clear()方法就可以释放了。

   2.T的类型为指针的情况,这时候直接调用clear()方法将不能释放,需要把每个对象delete。

该部分摘自:https://blog.csdn.net/fanbingyu85/article/details/9704905

方式1:一个个删除节点:

QHash<QString, QUserInfo*>::const_iterator j = m_hash.constBegin();
QHash<QString, QUserInfo*>::const_iterator delIndex = j;
while ((delIndex = j) != m_hash.constEnd()) 
{
    qDebug() << delIndex.key();
    QUserInfo* userInfo = (QUserInfo*)delIndex.value();
    
    if (userInfo != NULL)
    {
        delete userInfo;
        userInfo = NULL;
    }
    ++j;
    
    m_hash.remove(delIndex.key());
}


方式2:删除全部节点:

QHash<QString, QUserInfo*>::const_iterator j = m_hash.constBegin();
while (j != m_hash.constEnd()) 
{
    qDebug() << j.key();
    QUserInfo* userInfo = (QUserInfo*)j.value();
    
    if (userInfo != NULL)
    {
        delete userInfo;
        userInfo = NULL;
    }
    ++j;
}
m_hash.clear();

我自己借鉴用的删除全部节点,执行ok。

方式3:

看其他人有用 void qDeleteAll ( const Container & c )

Example:

 QList list; list.append(new Employee("Blackpool", "Stephen")); list.append(new Employee("Twist", "Oliver")); qDeleteAll(list.begin(), list.end()); list.clear();
我没试验成功,大家可以试试。

你可能感兴趣的:(Qt,Learn)