#include <QList>
#include <QtDebug>
class Foo
{
public:
Foo()
{
qDebug("Empty constructor");
}
Foo(int aa, int bb, int cc) : a(aa), b(bb), c(cc)
{
qDebug("Constructor");
}
Foo(const Foo &f)
{
a = f.a;
b = f.b;
c = f.c;
qDebug("Copy constructor");
}
int a, b, c;
};
int main(int /*argc*/, char ** /*argv*/)
{
QList<Foo> list;
list << Foo(1, 2, 3);
list << Foo(4, 5, 6);
list << Foo(7, 8, 9);
list << Foo(10, 11, 12);
list << Foo(13, 14, 15);
foreach(Foo f, list)
f.a = f.b = f.c = 0;
foreach(Foo f, list)
qDebug() << f.a << f.b << f.c;
}
There are two problems in the usage of foreach in this code.
The first problem is serious, it is trying to use foreach to modify the values of vector. The code compiles, but if you run it, you'll notice nothing was changed, why oh why?! may you ask. Because Foo f is a local variable to the foreach, so what you are doing is modifying a variable that exists in this very same line and nothing more.
The second problem is that you are constructing far much more Foo objects than needed, if you look at the output the copy constructor is called each time in the foreach, so the correct way for the debug line would be
foreach(const Foo &f, list)
qDebug() << f.a << f.b << f.c;
}
So remember, always that your foreach iterator is not a basic value like an int, double or pointer, use const &, it will be faster and will protect you against the try to use foreach to modify values problem, because
foreach(const Foo &f, list)
f.a = f.b = f.c = 0;
will not compile.