简体   繁体   中英

'colon' and 'auto' in for loop c++? need some help understanding the syntax

I need some explanation for the following c++ syntax:

for(const auto& ioDev : deviceList)

given that:

std::vector<Device *> deviceList

Specifically, I am confused about ':' and the usage of 'auto'?

This is a range based for loop, it has the same basic behavior of:

for(auto it = deviceList.begin(); it != deviceList.end(); ++it)
{
   const auto& ioDev = *it;
}

The range based for loop has quickly become one of my favorite constructs, it's terse and when you need to iterate an entire range, works as well (and as efficiently) as possible.

If you need the other constructs of a typical for loop (say to exit early in some case), then range-based for isn't for that use case.

As described in the answer by Chad, your for-loop iterates over your vector , using its begin and end iterators. That is the behavior of the colon : syntax.

Regarding your const auto & syntax: you should imagine what code comes out of it:

// "i" is an iterator
const auto& ioDev = *i;

The expression *i is (a reference to) the type of elements in the container: Device * . This is the deduced type of auto . Because you have const & appended to your auto , the variable ioDev is a const reference to the deduced type (a pointer), as if it were declared this way:

const Device *& ioDev = *i;

It seems needlessly complicated; if you need just normal iteration (and not eg manipulating the address of the pointer, which I think is highly unlikely), use a plain unmodified auto :

for (auto ioDev : deviceList)

or an explicit type:

for (Device* ioDev : deviceList)

The "new" for loop simply iterates over all the elements of deviceList . In each iteration of the body of the loop, ioDev is a const reference to each of the elments of deviceList , successively.

As to the type of ioDev : it is of type Device *const & , as you can see in the following:

#include <vector>                                                                                                                                                                                            
#include <type_traits>


using namespace std;


int main()
{
    vector<int *> v;

    for(const auto &r: v)
    {
        static_assert(is_same<decltype(r), int *const &>::value, "wrong type");
    }
}

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