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

Dan Bernstein mitz at apple.com
Thu Jan 2 13:40:47 PST 2014


On Jan 2, 2014, at 1:12 PM, Geoffrey Garen <ggaren at apple.com> wrote:

> 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.

We tend to avoid local write-once-read-once local variables, i.e. we tend to prefer

{
    setSize(optimalSize());
}

to

{
    CGSize newSize = optimalSize();
    setSize(newSize);
}

But the up- and down-sides of this are the same as those of using auto. Do you think we should also encourage use of write-once-read-once locals for the same reasons?


More information about the webkit-dev mailing list