C++11 new feature: auto type deduction
FangLu 2700058AGP Comments (2) Visits (10146)
In the C++11 standard, the auto keyword is no longer a storage class specifier, but acts as a type specifier that directs the compiler to deduce the type of a declared variable from its initialization expression.
With the auto type deduction feature 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. For example:
auto i = 1.1; // i : double
You can also qualify the auto keyword with cv-qualifiers, pointer(*) and reference(&) declarators. For example:
auto x = pd; // x : double*
auto* y = pd; // y : double*
auto x = g(); // x : int
const auto& y = g(); // y : const int&
You can also declare multiple variables in a single auto declaration statement. For example:
auto x = 1.2, y = 3.9; // x : double, y : double
In case of multiple variable declarations, the type of each declarator can be deduced independently. If the deduced type is not the same in each deduction, the program is ill-formed. For example, in the following statement, y is deduced as double, but was previously deduced as int.
auto x = 3, y = 1.2; //error
auto can be applied to the new expression. For example:
auto* p = new auto(1); // p : int *
auto cannot deduce array types. For example:
auto b = a; // error, a evaluates to a pointer, which does
// not match the array type
auto can not be used in function parameters. For example:
int func(auto x = 3); //error, parameter declared 'auto'
From the previous examples, we can see that the auto type deduction feature can increases programming convenience, potentially eliminates typing errors, and simplifies your code.