auto&的含义: [英] Meaning of auto& :

查看:53
本文介绍了auto&的含义:的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道自动意味着类型推导.我从未见过将它用作 auto& ,而且我不明白:在这段短代码中的作用.

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.

#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.

推荐答案

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

You are almost correct with your sample code.

在C ++ 11中自动定义了自动含义.编译器将推断出正在使用的变量的正确类型.

Auto meaning was redefined in C++11. The compiler will inferer the right type of the variable that is being used.

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

The syntax with : it's a range based for. It means that loop will parse each element inside threads vector.

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

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 thread variable. In this way every operation done on the thread var is done on the element inside the threads vector. Moreover, in a range-based for, you always want to use a reference & for performance reasons.

这篇关于auto&amp;的含义:的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆