views:

224

answers:

1

I'm working on a very basic game and I have a std::list collection of objects that pertain to my game. I declared it as:

std::list<Target> targets;

When I iterate over it, using

for (std::list<Target>::iterator iter = targets.begin(); iter != targets.end(); iter++) {
     Target t = *iter;
                t.move();
}

My objects aren't updating on the GUI. However, replacing the iterating loop with a targets.front().move(), my one object moves correctly. I think this is because I am not iterating over the collection using pointers. Can anyone explain how that is done? Thanks.

+3  A: 

You are copying the objects, do it this way:

*iter.move()

If you use Target t = *iter; you are essentially making a copy of your object and moving it, instead of moving your intended object.

As xtofl said(thx) you can get the reference as well.

Target &t = *iter;
t.move();
Arkaitz Jimenez
Or use `Target`.
xtofl
tipu
Or use `iter->move();`
Kirill V. Lyadvinsky
I believe `*iter.move()` has the operator precedence wrong; if you want to do it that way, it should be `(*iter).move()`. But `->` is easier.
int3
`(*iter).move();` is the same as `iter->move();`. It's just syntactic sugar added in C++.
Evän Vrooksövich
`(*iter).move()` is the same as `iter->move()` because this is the way these operators are required to work for `list::iterator`. `->` operator is only "syntactic sugar" when it is a built=in `->`. Once we get to overloading, this is a completely different operator, not a "syntactic sugar".
AndreyT