简体   繁体   中英

What type is in the range for loop?

#include <vector>
#include <iostream>

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

To what is auto expanding? Is it expanding to int& or int ?

It expands to int. If you want a reference, you can use

for ( auto& it : v )
{
    std::cout<<it<<std::endl;
}

According to the C++11 standard, auto counts as a simple-type-specifier [7.1.6.2], thus the same rules apply to it as to other simple-type-specifiers . This means that declaring references with auto is no different from anything else.

I created another example, which answers the question :

#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;
}

It is obvious that the auto expands to int , and the copy is being made. To prevent copying, the for loop needs to be with a reference :

for ( auto & it : v )

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM