Consider the following simple code in C++11, taken from C++ Primer, 5th Edition:
#include <iostream>
#include <string>
using std::cout;
using std::string;
using std::endl;
int main()
{
string s("Hello World!!!");
for (auto &c : s) // for every char in s (note: c is a reference)
c = toupper(c); // c is a reference, so the assignment changes the char
cout << s << endl;
return 0;
}
The code uses a range for
loop to iterate over every character in a string
and change it to uppercase, which is pretty straightforward. What puzzles me is that the reference c
seems to change at runtime. Elsewhere in the book, the authors mention that references, not being objects, cannot change in runtime. Can anyone shed some light into how exactly is this code interpreted by the compiler?
You're right that a reference can't be changed to refer to a different object; it must be initialised to refer to a particular object, and remains an alias for that object for its whole lifetime.
In this case, the reference doesn't change; instead, a new reference is created and destroyed for each iteration of the loop. This range-style loop is defined to be (more-or-less) equivalent to the old-style loop
for (auto it = s.begin(); it != s.end(); ++it) {
auto &c = *it;
// loop body
}
Written like this, it's clear that there's a new reference each time, not a single reference that's (somehow) updated.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With