Che*_*ele 4 c++ reference c++11
考虑以下C++ 11中的简单代码,取自C++ Primer,第5版:
#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;
}
Run Code Online (Sandbox Code Playgroud)
代码使用range for循环迭代a中的每个字符string并将其更改为大写,这非常简单.令我困惑的是,引用c似乎在运行时发生了变化.在本书的其他地方,作者提到引用而不是对象不能在运行时改变.任何人都可以了解编译器如何解释这段代码?
你是对的,不能改变引用来引用不同的对象; 必须将其初始化为引用特定对象,并在整个生命周期内保留该对象的别名.
在这种情况下,参考不会改变; 相反,为循环的每次迭代创建和销毁新的引用.这个范围风格的循环被定义为(或多或少)等效于旧式循环
for (auto it = s.begin(); it != s.end(); ++it) {
auto &c = *it;
// loop body
}
Run Code Online (Sandbox Code Playgroud)
写得像这样,很明显每次都有一个新的引用,而不是一个(以某种方式)更新的引用.