簡體   English   中英

在C ++ 11中顯然在運行時更改引用

[英]Reference apparently changing at runtime in 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;
}

代碼使用range for循環來迭代string每個字符並將其更改為大寫,這非常簡單。 令我困惑的是,引用c似乎在運行時發生了變化。 在本書的其他地方,作者提到引用而不是對象不能在運行時改變。 任何人都可以了解編譯器如何解釋這段代碼?

你是對的,不能改變引用來引用不同的對象; 必須將其初始化為引用特定對象,並在整個生命周期內保留該對象的別名。

在這種情況下,參考不會改變; 相反,為循環的每次迭代創建和銷毀新的引用。 這個范圍風格的循環被定義為(或多或少)等效於舊式循環

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

寫得像這樣,很明顯每次都有一個新的引用,而不是一個(以某種方式)更新的引用。

對於for (auto &c : s)的每次迭代,都會創建一個新的c ,在迭代結束時c超出范圍。

以下大致相同

for(int i = 0; i < s.length(); i++)
{
    auto &c = *(s+i);
    /*
        Do Stuff;
    */
}

被引用內容的值隨此代碼而變化。 但是在定義參考的整個范圍內,即(帶括號)

for (auto &c : s){ // for every char in s (note: c is a reference)
    c = toupper(c);
}

引用指的是相同且唯一的變量。 隨着循環的每次迭代,您將獲得對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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM