In C++03, auto
specifies that a variable has automatic storage duration. This means that the variable is destroyed when it falls out of scope. This contrasts with static
variables which persist for the lifetime of the program.
Since the default storage duration is auto
, the specifier is usually omitted.
In C++11, the auto
keyword has an additional use, namely automatic type deduction.
Consider the C++03 statement:
XmlParser parser = new XmlParser();
In C++11, we can write:
auto parser = new XmlParser();
In the second case, we are leaving it up to the compiler to deduce that parser
is of type XmlParser
.
In some cases, the auto
keyword can significantly simplify syntax and lead to more readable code. For example:
std::map<std::string, int> mymap;
for (std::map<std::string, int>::iterator it = mymap.begin(); it != mymap.end(); ++it)
{ ... }
can be simplified to the following:
std::map<std::string, int> mymap;
for (auto it = mymap.begin(); it != mymap.end(); ++it)
{ ... }
We shall discuss some other improvements to loop syntax in Range-based Loop Syntax.