Reputation: 50
In Qt I understand that if you create an object that inherits from QObject and set it's parent, then the parent is responsible for deleting the children. I also understand that if you create objects on the stack that they are deleted when they go out of scope.
I'm not wrapping my head around the case where I want to explicitly delete items in a QStringList ( or any QList ) and then the list itself.
Consider if I create a QStringList and populate it like below:
QStringList multiPartPortionList;
multiPartPortionList = multiPartPortion.split(QRegExp("[\r\n]"),QString::SkipEmptyParts);
Then I do stuff with it and call this method in attempt to explicitly delete the items contained within the list and then the list itself:
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;
}
I can't call qDeleteall(list) because it expects a pointer, and I also can't do just do:
delete list;
Since it errors with 'argument given to 'delete', expected pointer', expecting a pointer.
I get segmentation faults with:
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;
}
I also get segmentation faults with:
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;
}
And then I also get segmentation faults with:
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
}
I don't think this is quite, or even close, to being right. How can I best achieve what I want - that is to explicitly delete all items in a list and then the list itself?
Upvotes: 0
Views: 5458
Reputation: 6999
Your QStringList list
gets deleted automagically at the end of the function. No need to worry about deleting pointers here.
In the same manner,
QStringList *delList = new QStringList(list);
should be
QStringList delList = QStringList(list);
better yet:
QStringList delList = list;
You should read about automatic storage and RAII. In your code, new
and delete
are superfluous.
To remove an element in the list, use removeAt. This has nothing to do with deleting.
I also suggest that you get a good book before continuing in C++.
Upvotes: 5