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

Filip Pizlo fpizlo at apple.com
Thu Jan 2 13:19:49 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.

I agree.

Code is read more than it is written.  In many cases, the types of variables - even nasty templated ones - convey useful information that makes the code easier to read.  I think that "auto" is only a good idea if the presence of the full type would be either completely redundant or would make the code hard to read by virtue of being unusually long (>80 chars, like some intense HashMap instantiations).  Crucially, while the C++ compiler has a smart type inference engine that can see a lot of code all at once, a typical human reader lacks such powers and so "auto" results in a net loss of information.

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

I like this.  I would like to see this be added to the style guide.

-Filip

> 
> Thanks,
> Geoff
> _______________________________________________
> webkit-dev mailing list
> webkit-dev at lists.webkit.org
> https://lists.webkit.org/mailman/listinfo/webkit-dev

-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.webkit.org/pipermail/webkit-dev/attachments/20140102/9bae184e/attachment.html>


More information about the webkit-dev mailing list