在Qt中,我理解如果你创建一个继承自QObject的对象并设置它的父对象,那么父对象负责删除子对象。我也明白,如果你在堆栈上创建对象,当它们超出范围时会被删除。
我没有把我的脑袋缠绕在我想要显式删除QStringList(或任何QList)中的项目然后列表本身的情况下。
考虑我是否创建了一个QStringList并填充如下:
QStringList multiPartPortionList;
multiPartPortionList = multiPartPortion.split(QRegExp("[\r\n]"),QString::SkipEmptyParts);
然后我做了一些事情并调用此方法试图明确删除列表中包含的项目,然后是列表本身:
void MyClass::deleteList(QStringList list) {
// Now cleanup
QStringList *delList = new QStringList(list);
int numObjects = delList->count();
for (int i=0; i < numObjects; i++)
delete (new QString(list.takeAt(0)));
delList->clear();
delete delList;
delList = 0;
}
我无法调用qDeleteall(list),因为它需要一个指针,我也不能这样做:
delete list;
由于错误的&#39;参数为&#39;删除&#39;,预期指针&#39; ,因此需要指针。
我得到了分段错误:
void MyClass::deleteList(QStringList list) {
// Now cleanup
QStringList *delList = &list; // <--- Seg fault with this
int numObjects = delList->count();
for (int i=0; i < numObjects; i++)
delete (new QString(list.takeAt(0)));
delList->clear();
delete delList;
delList = 0;
}
我也会遇到分段错误:
void MyClass::deleteList(QStringList list) {
// Now cleanup
QStringList *delList = &list;
int numObjects = delList->count();
for (int i=0; i < numObjects; i++)
delete &(list.takeAt(0)); // <--- Seg fault with this
delList->clear();
delete delList;
delList = 0;
}
然后我也会遇到分段错误:
void MyClass::deleteList(QStringList list) {
// Now cleanup
QStringList *delList = new QStringList(list);
int numObjects = delList->count();
for (int i=0; i < numObjects; i++)
delete (new QString(list.takeAt(0)));
delList->clear();
delete delList;
delList = 0;
delete &list; // <--- Seg fault with this
}
我不认为这是正确的,甚至是接近的。我怎样才能最好地实现我想要的 - 即明确删除列表中的所有项目,然后是列表本身?