循环范围内的类型是什么?

BЈо*_*вић 18 c++ c++11

#include <vector>
#include <iostream>

int main()
{
    std::vector< int > v = { 1, 2, 3 };
    for ( auto it : v )
    {
        std::cout<<it<<std::endl;
    }
}
Run Code Online (Sandbox Code Playgroud)

什么在auto扩大?是扩大到int&int

Tam*_*lei 18

它扩展到int.如果您想要参考,您可以使用

for ( auto& it : v )
{
    std::cout<<it<<std::endl;
}
Run Code Online (Sandbox Code Playgroud)

根据C++ 11标准,auto计为简单类型说明符 [7.1.6.2],因此相同的规则适用于其他简单类型说明符.这意味着声明引用与auto其他任何内容都没有区别.


BЈо*_*вић 5

我创建了另一个例子,回答了这个问题:

#include <vector>
#include <iostream>

struct a
{
    a() { std::cout<<"constructor" << std::endl; }
    a(const a&) { std::cout<<"copy constructor" << std::endl; }
    a(a&&) { std::cout<<"move constructor" << std::endl; }

    operator int(){return 0;}
};

int main()
{
    std::vector< a > v = { a(), a(), a() };

    std::cout<<"loop start" << std::endl;
    for ( auto it : v )
    {
        std::cout<< static_cast<int>(it)<<std::endl;
    }
    std::cout<<"loop end" << std::endl;
}
Run Code Online (Sandbox Code Playgroud)

很明显,auto扩展到了int,并且正在进行复制.为了防止复制,for循环需要带有引用:

for ( auto & it : v )
Run Code Online (Sandbox Code Playgroud)