Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

Why? You know foo has the type of "whatever 'it' dereferences to." Why would spelling it out be an improvement? Would your opinion change in a templated function where the type is, itself, a placeholder (e.g., "typename T")?

What if "it" were originally an unsigned int* but a refactoring changed that to a long*? Would you prefer the programmer hunt down all cases where "it" is dereferenced to change the type of the result, or would you prefer the programmer use "auto" to begin with?



The types of dereferenced iterators can be nasty. See for example std::map::iterator. Using an explicit type allows you to keep less in your head at once. It's good to give stuff names, and say what they are.

In a template, you're somewhat better off using Container::value_type. Though not by much.

The unsigned int* -> long* example is a good point. But auto doesn't fully solve that problem - consider something like iter = x or some_func(iter). The auto also makes it more work to figure out what the underlying type is. You're probably better off using a typedef.


You're certainly always allowed to use a typedef. I can just tell you from my experience that auto is more than "a nice thing to have in very specific circumstances." For me, at least, it's "a nice thing to have in almost all circumstances, with a handful of exceptions." When in doubt, I type "auto."




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: