The keyword auto
provides the auto-deduction of type of a variable.
It is especially convenient when dealing with long type names:
std::map< std::string, std::shared_ptr< Widget > > table;
// C++98
std::map< std::string, std::shared_ptr< Widget > >::iterator i = table.find( "42" );
// C++11/14/17
auto j = table.find( "42" );
with range-based for loops:
vector<int> v = {0, 1, 2, 3, 4, 5};
for(auto n: v)
std::cout << n << ' ';
with lambdas:
auto f = [](){ std::cout << "lambda\n"; };
f();
to avoid the repetition of the type:
auto w = std::make_shared< Widget >();
to avoid surprising and unnecessary copies:
auto myMap = std::map<int,float>();
myMap.emplace(1,3.14);
std::pair<int,float> const& firstPair2 = *myMap.begin(); // copy!
auto const& firstPair = *myMap.begin(); // no copy!
The reason for the copy is that the returned type is actually std::pair<const int,float>
!