在 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;
由于它与'argument given to 'delete', expected pointer'出错,需要一个指针。
我得到分段错误:
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
}
我不认为这是完全正确的,甚至是接近正确的。我怎样才能最好地实现我想要的 - 即显式删除列表中的所有项目,然后再删除列表本身?