In C++, it is allowed to iterate over every element of a container (let's take a vector for instance), like in

vector<CustomObject> container; //push back some objects in container for(CustomObject obj : container){ //process obj }

I have a question about the "for" behavior: is container copied to be used in the for or accessed by reference?

πάντα ῥεῖ's user avatar

πάντα ῥεῖ

89k13 gold badges127 silver badges201 bronze badges

asked Jul 17, 2018 at 17:49

Mickael Wajnberg's user avatar

1

The container is not being copied. It's being accessed by reference. However, the CustomObject is being copied for each loop. The compiler may optimize away the copy, but that is not guaranteed.

To prevent the copying of CustomObjectin this example, you'd do this: for(CustomObject& obj : container)

answered Jul 17, 2018 at 17:52

Gabriel's user avatar

1 Comment

Should be const CustomObject& unless modification of the values is desired.

2018-07-17T17:53:23.573Z+00:00

The container is not copied. However, every element within it is copied. You can change this by specifying it using the ampersand. That is:

for (CustomObject &obj : container) { // Process obj }

Usually the best decision when dealing with large containers.

answered Jul 17, 2018 at 17:54

swandog's user avatar

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.