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

Geoffrey Garen ggaren at apple.com
Thu Jan 2 13:12:46 PST 2014


Hi folks.

Recently, I’ve seen patches go by using the C++11 “auto” keyword. For example, let me pick on Andreas:

> <http://trac.webkit.org/changeset/161143>
> 
> +    auto newRenderer = textNode.createTextRenderer(style);
> +    ASSERT(newRenderer);
> 
> ….
> 
> +    parentRenderer->addChild(newRenderer.leakPtr(), nextRenderer);

I think this use of “auto” is net harmful. 

Upsides:

- Less typing

Downsides:

- I don’t know the type of ’newRenderer’ at a glance
- Navigating to newRenderer’s class definition is a two-step process: (1) Go to the definition of createTextRenderer and see what it returns; (2) Go to the definition of (1).

I think the downsides outweigh the upsides here because reading code is more common than writing code, and because it’s not *that* much typing to write out "RenderPtr< RenderText>”. In this particular code, I think it’s especially bad to disguise the type of a pointer in the render tree, since we’re in the middle of a transition to a new type of pointer, and so it’s important to know if you’re looking at code that does the new thing or the old thing.

I think an appropriate style guideline for “auto” would say something like:

- Use “auto" to declare a disgusting templated iterator type in a loop
- Use “auto… ->" to define a template-dependent return type in a class template
- In all other cases, use an explicit type declaration

Thoughts?

Thanks,
Geoff


More information about the webkit-dev mailing list