Does Qt foreach expression require a deep copy?

I have a problem with the Qt foreach function. I have a Phrase class, which is a subclass of QList. In ~ Phrase, I delete all GlossItem pointers.

In an iteration using GlossItem pointers in a phrase, I would like to use Qt 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 doing a deep copy on Phrase (I know this because I needed to implement a copy constructor). But if there is a copy of the phrase - and if I do not want to create a deep copy of each GlossItem, it means that these pointers will be deleted twice. (Or deleted once, and then worked.) So I have to use this, which works, but is less beautiful.

  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?

+4
source share
2 answers

From the documents

Qt automatically takes a copy of the container when it enters the foreach loop.

and

Since foreach creates a copy of the container, using a non-constant reference for the variable does not allow you to modify the original container.

So, I think that foreach not suitable for your particular case, otherwise you will get a new copy of Phrase with extra pointers, instead of returning the actual original Phrase you want.

+6
source

No, if you look at the code extended from foreach : qt.gitorious.org/qt/qt/blobs/HEAD/src/corelib/global/qglobal.h#line2371 It uses const_iterator. Yes, it copies the container, but since the entire container class in Qt is implicit, it is only a shallow copy, not a deep one.

+1
source

All Articles