C++ 在C+;中,引用在运行时发生明显变化+;11

C++ 在C+;中,引用在运行时发生明显变化+;11,c++,c++11,reference,C++,C++11,Reference,考虑以下C++11中的简单代码,摘自: #包括 #包括 使用std::cout; 使用std::string; 使用std::endl; int main() { 字符串s(“你好,世界!!!”; for(auto&c:s)//对于s中的每个字符(注意:c是一个引用) c=toupper(c);//c是一个引用,因此赋值会更改字符 cout被引用内容的值随代码的变化而变化。但在定义引用的整个范围内,即(使用大括号) 引用引用了相同且唯一的变量。循环的每次迭代都会得到对s中下一个元素的新引用 实际

考虑以下C++11中的简单代码,摘自:

#包括
#包括
使用std::cout;
使用std::string;
使用std::endl;
int main()
{
字符串s(“你好,世界!!!”;
for(auto&c:s)//对于s中的每个字符(注意:c是一个引用)
c=toupper(c);//c是一个引用,因此赋值会更改字符

cout被引用内容的值随代码的变化而变化。但在定义引用的整个范围内,即(使用大括号)

引用引用了相同且唯一的变量。循环的每次迭代都会得到对
s
中下一个元素的新引用

实际上,您不能使用引用来更改引用的内容,即:

int i = 10;
int j = 20;
int& h = i;// j now refers to i
h = j; // modifies i, doesn't change what it refers to from i to j

您是对的,引用不能更改为引用其他对象;它必须初始化为引用特定对象,并在该对象的整个生命周期中保持别名

在这种情况下,引用不会更改;相反,会为循环的每次迭代创建并销毁一个新引用。此范围样式循环定义为(或多或少)等同于旧样式循环

for (auto it = s.begin(); it != s.end(); ++it) {
    auto &c = *it;
    // loop body
}

这样写的话,很明显每次都会有一个新的引用,而不是一个(以某种方式)更新的引用。

对于(auto&c:s)
每次迭代,都会创建一个新的
c
,在迭代结束时
c
超出范围

以下内容大致相当:

for(int i=0;i
的范围
是语法糖。
int i = 10;
int j = 20;
int& h = i;// j now refers to i
h = j; // modifies i, doesn't change what it refers to from i to j
for (auto it = s.begin(); it != s.end(); ++it) {
    auto &c = *it;
    // loop body
}
for(int i = 0; i < s.length(); i++)
{
    auto &c = *(s+i);
    /*
        Do Stuff;
    */
}