[webkit-dev] When to use "auto"? (I usually consider it harmful)

Geoffrey Garen ggaren at apple.com
Thu Jan 2 15:03:21 PST 2014

One interesting point in this article, which I tend to agree with, is that it seems generally appropriate to use “auto” in any line of code that already conveys type. For example:

(1) Lambda, as pointed out by Alexey:

    auto failureCallback = [promiseWrapper]() mutable {

(2) Integer declaration:

    auto x = 42ul;

(3) Simple heap allocation:

    auto buffer = std::make_unique<UniChar[]>(length);

So, I’d add that to the list of places to use “auto”:

- Use “auto" to declare an iterator type
- Use “auto… ->" to define a template-dependent return type in a class template
- Use “auto” when the right hand side of the expression already denotes type
- In all other cases, use an explicit type declaration

But I’m not convinced by the article’s conclusion that we should just use auto everywhere, and use "auto x = type{ init }” when we want to commit to a specific type. I think that solution would open up a can of worms. Reasonable people would routinely disagree about exactly which lines of code needed to “commit to a specific type”. A style guide should be as black-and-white as possible. “… when we want to …” is basically a cop out for a style guide.

I’m also not convinced by the article’s generalization from a simple algorithmic helper function to a whole code base. Algorithmic helper functions can, indeed, be written in terms of generic well-known names. I guess that’s why I think that iterators should be auto: “begin", “end", “*”, “->” and “++" are about as well-known as it gets. But not all problems are simple general-purpose algorithms with well-known names. Many problems require you to think explicitly about the data. And I’d rather not add statements about data to our names, a la Hungarian (sic) notation.


On Jan 2, 2014, at 2:08 PM, Adam Roben <aroben at webkit.org> wrote:

> I found http://herbsutter.com/2013/08/12/gotw-94-solution-aaa-style-almost-always-auto/
> very persuasive in my thinking about when to use auto.
> -Adam
> _______________________________________________
> webkit-dev mailing list
> webkit-dev at lists.webkit.org
> https://lists.webkit.org/mailman/listinfo/webkit-dev

More information about the webkit-dev mailing list