Pointers and References
For simple type declarations, the use of
auto is rather intuitive. However, what happens when the initializer is a reference?
int& myfunc();
int yourfunc();
auto j=myfunc(); //int& or int?
The authors decided to apply the same rules of template type deduction. The type of
j is therefore
int, not
int&. To create an
auto reference variable, you need to use this form:
auto& j=myfunc(); // int&
Similarly, to add cv-qualification to the variable, use this syntax:
const auto& ci=yourfunc(); //const int&
If the initializer is a pointer, the compiler will deduce the pointer's type and assign it to the auto variable. You can omit the * in an
auto declaration if the initializer is a pointer:
int n;
auto pi=&n;//pi is int*
auto* pi2=&n; //also int*
auto* p = new Myclass; //Myclass*
auto p2 = new Myclass //Myclass *
Notice however that the compiler will deduce the type based on the entire initializer expression. In the following example, the type of
q is
Myclass, not
Myclass*:
auto q= *new Myclass;
Similarly,
auto can be used in a
new expression:
new auto('s');
The type of
auto('s') is
char. Therefore, the type of the expression
new auto('s') is
char *. Here's another example:
new auto(1000LL); //new long long*.
const auto p= new auto(1000LL); //p is const long long*
Multi-Variable Declarations
Originally, the auto proposal allowed only one variable to be declared in every auto statement. This restriction was later removed, so now you can declare multiple variables in a single auto statement:
auto a=6.8, *pa = &a; //a is double, pa is double*
According to the latest version of the
auto proposal, the status of array declarations isn't clear. At the time of writing, the following isn't allowed:
auto arr[]={1,2,3,4};//error, arrays aren't allowed
Similarly, the status of this borderline case is also being debated:
int x[4];
auto y = x; // int*?
Ready to Use
The new syntax for automatic type deduction simplifies your code by eliminating unwieldy type names from declarations and expressions.
Several issues with
auto still need to be resolved, though: array declarations, typedefs, and pointers to functions. At present, some implementations already support
auto,
Comeau for instance, so you don't have to wait for the ratification of the C++0x standard to start using this feature.