C++ – Should I use the new C++11 ‘auto’ feature, especially in loops

cc++11

What are the pros/cons to using the auto keyword, especially in for loops?

for(std::vector<T>::iterator it = x.begin(); it != x.end(); it++ )
{
   it->something();
}

for(std::map<T>::iterator it = x.begin(); it != x.end(); it++ )
{
   it->second->something();
}

for(auto it = x.begin(); it != x.end(); it++ )
{
   it->??
}

Seems like if you don't know whether you have an iterator for a map or a vector you wouldn't know whether to use first or second or just directly access properties of the object, no?

This reminds me of the C# debate on whether to use the keyword var. The impression I'm getting so far is that in the C++ world people are ready to adopt the auto keyword with less of a fight than var in the C# world. For me my first instinct is that I like to know the type of the variable so I can know what operations I can expect to perform on it.

Best Answer

The motivations in C++ are more extreme, as types can become vastly more convoluted and complex than C# types due to metaprogramming and other things. auto is faster to write and read and more flexible/maintainable than an explicit type. I mean, do you want to start typing

boost::multi_map<NodeType, indexed_by<ordered_unique<identity<NodeType>>, hashed_non_unique<identity<NodeType>, custom_hasher>>::iterator_type<0> it

That's not even the full type. I missed off a couple template arguments.

Related Topic