C++11 introduces the keyword auto as a new type specifier. auto acts as a placeholder for a type to be deduced from the initializer expression of a variable. With auto type deduction enabled, you no longer need to specify a type while declaring a variable. Instead, the compiler deduces the type of an auto variable from the type of its initializer expression.
auto x = 1; //x : int
float* p;
auto x = p; //x : float*
auto* y = p; //y : float*
double f();
auto x = f(); //x : double
const auto& y = f(); //y : const double&
class R;
R* h();
auto* x = h(); //x : R*
auto y = h(); //y : R*
int& g();
auto x = g(); //x : int
const auto& y = g(); //y : const int&
auto* z = g(); //error, g() does not return a pointer type
By delegating the task of type deduction to the compiler, auto type deduction increases programming convenience, and potentially eliminates typing errors made by programmers. Auto type deduction also reduces the size and improves the readability of programs.
vector<int> vec;
for (vector<int>::iterator i = vec.begin(); i < vec.end(); i++)
{
int* a = new int(1);
//...
}
With auto type deduction enabled, the first example can
be simplified as follows:vector<int> vec;
for (auto i = vec.begin(); i < vec.end(); i++)
{
auto a = new auto(1);
//...
}
int x[5];
auto y[5] = x; //error, x decays to a pointer,
//which does not match the array type
int f();
auto& x = f(); //error, cannot bind a non-const reference
//to a temporary variable
int& g();
auto y = g(); //y is of type int
auto& z = g(); //z is of type int&
auto x=3, y=1.2, *z=new auto(1); //error y: deduced as double,
//but was previously deduced as int
auto x = x++; //error
int func(auto x = 3) //error
{
//...
}