我知道 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;
}
我猜这是某种合成糖的替代
for(std::vector<std::thread>::iterator it = threads.begin(); it != threads.end(); it++ ) {
(*it).join();
}
但我不明白这个语法是如何工作的,以及 & 符号在那里做什么。
最佳答案
您的示例代码几乎是正确的。
在 C++11 中重新定义了自动含义。编译器将推断出正在使用的变量的正确类型。
:
的语法是基于范围的。这意味着循环将解析线程 vector 中的每个元素。
在 for 中,您需要指定别名 auto&
以避免在 thread
变量中的 vector 内创建元素的拷贝。这样,在 thread
var 上完成的每个操作都是在 threads
vector 内的元素上完成的。此外,在基于范围的 for 中,出于性能原因,您总是希望使用引用 &
。
关于c++ - auto& :的含义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19414299/