【发布时间】:2021-05-17 11:21:02
【问题描述】:
我正在尝试删除(释放内存)QList 中指向 QByteArrays 的指针的所有 QByteArrays。这是我的代码:
在我的 .h 文件中
QList<QByteArray*> GroupWord; //declare the QList
在我的 .cpp 文件中
quint8 k = GroupWord.length(); //get the last Index
QByteArray& ref = *GroupWord.at(k - 1); //get the last Index
qDebug() << "Length before deletion: " << GroupWord.length(); //print out the length before deletion
qDebug() << "Before deletion: " << *GroupWord.at(k - 1); //print out before del
GroupWord.at(k - 1)->~QByteArray(); //destroy the entry
qDebug() << "Length after deletion: " << GroupWord.length(); //print out the length after deletion
*GroupWord.at(k - 1)->append('l'); //append to the 'assumed' deleted entry
qDeleteAll(GroupWord); //qDeleteAll the QList
qDebug() << "After deletion 1: " << ref; //print out the ref to entry
qDebug() << "After deletion 2: " << *GroupWord.at(k - 1); //print out entry
qDebug() << "After deletion 3: " << GroupWord.at(k - 1); //print out the pointer
GroupWord.clear();
qDebug() << "After deletion 4: " << ref; //the memory is still there after ~QByteArray() and qDeleteAll() =(((((
以下是我如何知道有问题的 QByteArray 没有被删除:
~QArrayByte();之后QList的长度还是一样的
我真的不知道这里发生了什么:(
我知道我不应该像这样声明变量,而只是将它传递给 void;当 QList 超出范围时,它将被自动删除。但是,我只是想测试一下:(
非常感谢你们,
祝你有美好的一天,:X
【问题讨论】:
-
您的代码中有多种未定义行为的原因:1) 在已经显式调用其析构函数的对象上调用
delete和 2) 访问QList元素而不首先检查其有效性索引(QList::at不执行边界检查)。 -
@G.M.我不知道;但是我已经编辑了我的代码以显示在执行
~QByteArray()之后 QList 的长度仍然相同。我做错什么了吗? : -
QByteArray对象在其析构函数被调用后不存在 -- 它的生命周期已经结束。访问它使用的内存(通过GroupWord.length())是未定义的行为。 -
@G.M.我不确定我是否正确理解:QList 的
QByteArray*;我只想销毁/释放用于 GroupWord 的最后一个索引的内存,这个最后一个索引本身是一个QByteArray指针。并且在调用QByteArray::~QByteArray之后,指针仍然存在,它没有设置为null,或者它应该是什么。 -
是的,这很好,因为对象被销毁了。
标签: c++ qt memory-management qlist qbytearray