ARTICLE AD BOX
Asked 7 years, 10 months ago
Viewed 2k times
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?
89k13 gold badges127 silver badges201 bronze badges
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)
Explore related questions
See similar questions with these tags.

