问题
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?
回答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)
回答2:
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.
来源:https://stackoverflow.com/questions/51387535/c-range-based-for-loop-is-the-container-copied