Possible Duplicate:
How much is too much with C++0x auto keyword
Have we (as a community) had enough experience to determine when and/or whether auto is being abused?
What I am really looking for is a best practices guide on
- when to use auto
- when it should be avoided
Simple rules of thumb that can quickly be followed in 80% of cases.
As a context this question is sparked by my response here
I think when the type is very well-known amongst the co-programmers who work (or would work) in your project, then
autocan be used, such as in the following code:Or, more generally,
But when the type is not very well-known and infrequently used , then I think
autoseems to reduce readability, such as here:While in the former case, the usage of
autoseems very good and doesn’t reduce readability, and therefore, can be used extensively, but in the latter case, it reduces readabilty and hence shouldn’t be used.Another place where
autocan be used is when you usenew1 ormake_*functions , such as here:Here it is very good, as it reduces the use of keyboard, without reducing the readability, as anyone can know the type of objects being created, just by looking at the code.
1. Avoid using
newand raw-pointers though.Sometime, the type is so irrelevant that the knowledge of the type is not even needed, such as in expression template; in fact, practically it is impossible to write the type (correctly), in such cases
autois a relief for programmers. I’ve written expression template library which can be used as:Output:
Now compare the above code with the following equivalent code which doesn’t use
auto:As you can see, in such cases
automakes your life exponentially easier. The expressions used above are very simple; think about the type of some more complex expressions:The type of such expressions would be even more huge and ugly, but thanks to
auto, we now can let the compiler infer the type of the expressions.So the bottomline is: the keyword
automight increase or decrease clarity and readability of your code, depending on the context. If the context makes it clear what type it is, or at least how it should be used (in case of standard container iterator) or the knowledge of the actual type is not even needed (such as in expression templates), thenautoshould be used, and if the context doesn’t make it clear and isn’t very common (such as the second case above), then it should better be avoided.