Unexpected behavior with std::vector during range-based for loop in C++17
I'm performance testing and I'm refactoring my project and I'm encountering an unexpected issue when using a range-based for loop with a `std::vector` of custom objects in C++17. My custom class has a non-trivial destructor and I've overridden the copy constructor and assignment operator to manage resources properly. However, when I iterate over the vector, it seems that the objects are being copied unnecessarily, which raises concerns about memory management and performance. Here's a simplified version of my code: ```cpp #include <iostream> #include <vector> class MyClass { public: MyClass() { std::cout << "Constructed" << std::endl; } MyClass(const MyClass& other) { std::cout << "Copied" << std::endl; } MyClass& operator=(const MyClass& other) { std::cout << "Assigned" << std::endl; return *this; } ~MyClass() { std::cout << "Destructed" << std::endl; } }; int main() { std::vector<MyClass> myVector(3); for (const auto& obj : myVector) { // Do something with obj } return 0; } ``` When I run this code, I see that the "Copied" message is printed for each object in the vector during the iteration, which I didn’t expect. I believed that using the `const auto&` reference in the range-based for loop would avoid unnecessary copies. I've also tried changing the loop to `for (auto& obj : myVector)` and `for (const MyClass& obj : myVector)` with the same results. Is there something I’m missing regarding how C++ handles copying in range-based for loops with STL containers? Any insights would be greatly appreciated. How would you solve this?