[webkit-dev] When to use "auto"? (I usually consider it harmful)
shaeffer at neuralscape.com
Thu Jan 2 16:15:10 PST 2014
On Thu, Jan 02, 2014 at 01:12:46PM -0800, Geoffrey Garen 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.
> - Less typing
> - 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
I prefer to write types out, because it does help with understanding the code you are
working with. Although there are instances where auto is supposedly required, if you
want to write portable c++11 code. My understanding is you should use auto for named
lambdas, else the code won't be portable. I've never verified that, but I've
heard that is the case.
Karen Shaeffer Be aware: If you see an obstacle in your path,
Neuralscape Services that obstacle is your path. Zen proverb
More information about the webkit-dev