I am having a bit of a problem with Qt’s foreach function. I have a class Phrase, which is a subclass of QList. In ~Phrase I delete all of the GlossItem pointers.
In iterating through the GlossItem pointers in Phrase, I would like to use Qt’s foreach:
// phrase is a pointer to a Phrase object,
// which is a subclassed QList<GlossItem*>
foreach( GlossItem *glossItem , *phrase )
{
// use glossItem
}
For some reason foreach is performing a deep copy on Phrase (I know this because it required me to implement the copy constructor). But if there is a copy of Phrase — and if I don’t want to create a deep copy of each GlossItem — that means that those pointers will be deleted twice. (Or, deleted once, and then crash.) So I have to use this, which works but is less pretty.
for(int i=0; i<phrase->count(); i++ )
{
GlossItem *glossItem = phrase->at(i);
// use glossItem
}
Is there a way around this or do I just need to live with it?
From the docs
and
So I think for your specific use case
foreachisn’t suitable otherwise you end up with a fresh copy of thePhrasewith additional pointers, rather than returning the actual originalPhrasethat you want.