c++ - auto& :的含义

标签 c++ syntax

我知道 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/

相关文章:

c# - 使用 new 后跟大括号内的列表的语法是什么?

c - C中变量名下划线前分号的可能原因

python - SWIG:将 std::vector<std::vector<double>> 指针传递给 python

syntax - 如何在 Julia 中转发位置和关键字参数?

c++ - CMAKE_C_COMPILER "is not a full path to an existing compiler tool"

c++ - 递归寻路直到除法结果为 1

syntax - 如何在 MMT 中给出绝对 URI?获取 "unbound token: http"和 "ill-formed constant reference"

python - 为什么分号在python中工作?

c++ - 请递归帮助

java - 为什么纹理图像颜色与原点不同?