C++ 自动&的含义:
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19414299/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Meaning of auto& :
提问by Chemistpp
I understand that auto means type deduction. I've never seen it used as auto&and furthermore I don't understand what :is doing in this short code.
我知道 auto 意味着类型推导。我从未见过它被用作auto&,而且我不明白:这个短代码在做什么。
#include <iostream>
#include <vector>
#include <thread>
void PrintMe() {
std::cout << "Hello from thread: " << std::this_thread::get_id() << std::endl;
}
int main() {
std::vector<std::thread> threads;
for(unsigned int i = 0; i < 5; i++) {
threads.push_back(std::thread(PrintMe));
}
for(auto& thread : threads) {
thread.join();
}
return 0;
}
I can guess this is some sort of syntatic sugar that replaces
我猜这是某种替代的语法糖
for(std::vector<std::thread>::iterator it = threads.begin(); it != threads.end(); it++ ) {
(*it).join();
}
but I don't understand how this syntax works and what that & sign is doing there.
但我不明白这个语法是如何工作的,以及那个 & 符号在那里做什么。
回答by dynamic
You are almost correct with your sample code.
您的示例代码几乎是正确的。
Auto meaning was redefined in C++11. The compiler will inferer the right type of the variable that is being used.
在 C++11 中重新定义了自动含义。编译器将推断正在使用的变量的正确类型。
The syntax with :it's a range based for. It means that loop will parse each element inside threads vector.
:它的语法是基于范围的。这意味着循环将解析线程向量中的每个元素。
Inside the for, you need to specify the alias auto&in order to avoid creating a copy of the elements inside the vector within the threadvariable. In this way every operation done on the threadvar is done on the element inside the threadsvector. Moreover, in a range-based for, you always want to use a reference &for performance reasons.
在 for 内部,您需要指定别名auto&以避免在thread变量内创建向量内部元素的副本。通过这种方式,对threadvar 执行的每个操作都是对threads向量内的元素执行的。此外,在基于范围的 for 中,&出于性能原因,您总是希望使用引用。

