Auto

I am sure that I used the auto keyword once in a while during the early days. We used to be concerned with putting things in registers ... that was before optimizing compilers became better at generating code than we assembly language programmers were at writing it from scratch. auto was a holdover from those days, and auto was the implicit storage class of everything not declared static, extern, or register:

int i = 0;      // what you wrote.
auto int i = 0; // what the compiler knew you meant.

I grepped the entire pre-C++11 code base (which on 13 April 2011 is the entire code base) at Digital Gaslight before I wrote this article, and I found not one instance of the token "auto" used as a C++ keyword, so it is not surprising that it could be recycled into a better purpose.

And that better purpose is ...?

auto causes the type of the declared and defined object to be determined ("deduced" is the term used on page 154) by the defining expression on the RHS. The examples given in the standard are trivial:

auto x = 5; // OK: x has type int

But this is hardly useful, nor is it the intention and benefit of this new feature. Instead, take a look at this definition from some of my code (that probably looks like some of your code):

map<double, std::string>::iterator prfm = revFreqMap.begin();

This is an example of the type of thing that is well suited for auto-simplification. Replace the above line with this one:

auto prfm = revFreqMap.begin();

Now, you might ask how the compiler is supposed to resolve the ambiguity involved in knowing which one of these two legal statements should be interpreted to replace the word auto?

map<double, std::string>::iterator prfm = revFreqMap.begin();
map<double, std::string>::const_iterator prfm = revFreqMap.begin();

The easy answer is that there are now functions named cbegin() and cend() that return the const versions of the iterators, and thus eliminate any ambiguity. The more complicated fact is that you if you intended to get the const iterator, and you call begin() rather than cbegin(), you will get a slap on the wrist telling you that your non-const iterator will not work on a const object.

 

Last updated 2014-07-19T15:44:11+00:00.

Links to the standard

A discussion of auto can be found in section 7.1.6.4. A discussion of the type deduction process can be found in section 14.8.2.

Benefits

When a long and complicated type is not used often enough to warrant a typedef of its own, using the auto syntax will save tedium. Additionally, auto must have an initializer ... that's the way it works ... so using auto ensures that such objects have initializers, and that's a good thing.

Risks

When it comes to const, you will need to have your RHS evaluate to a const expression to get what you need.