2011-11-25 73 views
18
#include <vector> 
#include <iostream> 

int main() 
{ 
    std::vector<int> v = { 1, 2, 3 }; 
    for (auto it : v) 
    { 
     std::cout<<it<<std::endl; 
    } 
} 

什麼是auto擴大?是否擴大到int&int循環範圍中的類型是什麼?

+0

歷史上,auto關鍵字是一個存儲類型說明符,指示具有自動存儲類型(即在堆棧上分配)的對象。 – Oyeme

+9

@Oyeme:好的。但這與這個問題有什麼關係? – ereOn

+5

@Oyeme:在C++ 11中,'auto'意味着全新的東西。 –

回答

18

它擴展爲int。如果你想有一個參考,你可以使用

for (auto& it : v) 
{ 
    std::cout<<it<<std::endl; 
} 

按照C++ 11個標準,auto算作一個簡單類型說明符 [7.1.6.2],因此,同樣的規則也適用於作爲到其他簡單類型說明符。這意味着聲明與auto的引用與其他任何內容沒有什麼不同。

+0

您可能想要添加對標準的參考(原諒雙關語)以確保完整性。 – wilhelmtell

+0

@JohnDibling我想你誤解了這個功能。 'it'不是int,因爲容器'v'有一定數量的元素恰好在'int'範圍內,但是因爲'v'包含了整數。如果包含'SomeClass'元素,'it'的類型將是'SomeClass'。 –

+0

@wilhelmtell好的建議,但我沒有發現任何明確提到的自動說明符的引用,也沒有找到範圍聲明(我只是在標準中檢查了6.5.4和7.1.6.4)。我認爲這是自然而然的,這種類型是推導出來的,並用來代替'auto'。也可以寫'auto&it'。 –

5

我創造了另一個例子,它回答了這個問題:

#include <vector> 
#include <iostream> 

struct a 
{ 
    a() { std::cout<<"constructor" << std::endl; } 
    a(const a&) { std::cout<<"copy constructor" << std::endl; } 
    a(a&&) { std::cout<<"move constructor" << std::endl; } 

    operator int(){return 0;} 
}; 

int main() 
{ 
    std::vector<a> v = { a(), a(), a() }; 

    std::cout<<"loop start" << std::endl; 
    for (auto it : v) 
    { 
     std::cout<< static_cast<int>(it)<<std::endl; 
    } 
    std::cout<<"loop end" << std::endl; 
} 

很明顯的是,auto擴展到int,而該副本正在取得進展。爲了防止複製,for循環需要帶有引用:

for (auto & it : v) 
+0

它沒有回答這個問題,它只顯示了你的編譯器的行爲。 – wilhelmtell

+0

我認爲它確實回答,編譯器應該遵守標準,同時VJo恰好提交了與我在同一時間完全相同的答案,他刪除了它,並繼續提供更完整的答案,所以我很讚賞它,因爲它在那裏冷杉ST。 –