BЈовић
BЈовић

Reputation: 64223

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?

Upvotes: 18

Views: 431

Answers (2)

Tam&#225;s Szelei
Tam&#225;s Szelei

Reputation: 23941

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.

Upvotes: 18

BЈовић
BЈовић

Reputation: 64223

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 )

Upvotes: 5

Related Questions