我想知道如果使用auto
或其他類似聲明變量/ iterator/CallItWhatIsMoreAppropriate的東西)會每次都創建一個該項目的實例嗎?一個例子會說清楚:`auto`每次都創建一個新的變量實例?
void my_fun (std::unordered_map<std::string, std::string> & my_map) {
std::string search_str;
cin >> search_str;
while (search_str != "something") {
//Does the next line create an extra overhead each time?
auto search = my_map.find(search_str);
if (search != my_map.end())
{
std::cout << "found \n";
//I should be able to modify the element inside the map here.
} else {
my_map.insert({search_str, search_str});
}
cin >> search_str;
}
}
使用'auto'沒有任何開銷,並且您應該始終在可以正確初始化的地方定義變量。 –
@NeilButterworth我認爲這是一個重要的問題,只有在需要時才聲明變量,然後使用該實例,特別是聲明在循環內可以運行數百萬甚至數十億次。 –
「使用'auto'」在這裏並不意味着什麼。 'auto'只是類型名稱的替代品。你真正要問的是在循環中聲明一個_local變量_的後果。你的'search'是一個局部變量。這不是因爲你在聲明中使用了'auto';這是因爲你在哪裏宣佈它。 –