Monday, February 27, 2012

C++'11: auto keyword

auto keyword
Forget everything you know about the auto keyword. Section 7.1.1 of the standard forgot it like this:

The auto and register specifiers shall be applied only to names of objects declared in a block (6.3) or to function parameters (8.4). They specify It specifies that the named object has automatic storage duration (3.7.2). An object declared without a storage-class-specifier at block scope or declared as a function parameter has automatic storage duration by default. [Note: hence, the auto specifier is almost always redundant and not often used; one use of auto is to distinguish a declaration-statement from an expression-statement (6.8) explicitly.—end note]

Standards committee members searched through millions of lines of code and found only a few rare examples of its use, so they hijacked it for something everyone will use. It is now an auto initializer for variables. Borrowing heavily from the change submission [n1984] we will look at a few code examples:

auto x = 3.14; // x has type double

int foo();
auto x1 = foo(); //x1:int
const auto& x2 = foo(); //x2: const int&
auto& x3 = foo(); //x3: int&: error, cannot bind a reference to a temporary

float& bar();
auto y1 = bar(); //y1: float. Value semantics is the default (notice y1 is not of type float&)
const auto& y2 = bar(); //y2: const float&
auto& y3 = bar(); //y3: float&

A* fii();
auto* z1 = fii(); //z1: A*
auto z2 = fii(); //z2: A*
auto* z3 = bar(); //error, bar does not return a pointer type

The way it deduces the type to use is the same as how templates do it. i.e. in the code snipit:
const auto &i = expr;
The type of i is the deduced type of teh parameter u of teh call f(expr) of the following invented function template:
template void f(const U& u);
(see section 7.1.5.4 of the standard for the note on this)

You are even allowed to have multiple declarations on one line, but they must all be of the same type, just as if you specified the type. For example:
int i;
auto a = 1, *b = &1; //int and int*


The interesting thing that is missing is the ability to use auto with arrays. This is because an array decays into a pointer to the first element, which makes it difficult to specify the behavior in a way that is both consistent with the language and simple to understand. See section 8.3.4 paragraph 1, where it is explicitly banned.

No comments:

Post a Comment