汽车的含义:

Meaning of auto& :

本文关键字:汽车      更新时间:2023-10-16

我知道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();
}

但我不明白这种语法是如何工作的,以及那个和符号在那里做什么。

您的示例代码几乎是正确的。

自动含义在第 11 C++ 中重新定义。编译器将推断正在使用的变量的正确类型。

语法:它是基于范围。这意味着循环将解析线程向量中的每个元素。

在 for 中,您需要指定别名auto&以避免在 thread 变量中的向量内创建元素的副本。这样,对 thread var 执行的每个操作都是在 threads 向量内的元素上完成的。此外,在基于范围的 for 中,出于性能原因,您始终希望使用引用&