Synopsis: | Use a reference to a range based loop "auto" variable if it is modified in its body |
Language: | C++ |
Severity Level: | 2 |
Category: | Control Flow |
Description: |
Consider the following code std::vector<int> ints{ 10, 20, 30 }; for(auto i : ints) { if (i == 30) { i = 40; } } do something with "ints" Then after the for loop the "ints" variable will still be unchanged! Instead a reference to the "auto" variable should be used: std::vector<int> ints{ 10, 20, 30 }; for(auto& i : ints) { if (i == 30) { i = 40; } } do something with "ints" |
Literature References: |
StackOverflow C++11 range based loop: get item by value or reference to const |