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

Ryosuke Niwa rniwa at webkit.org
Thu Jan 2 16:54:53 PST 2014

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

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

On Thu, Jan 2, 2014 at 5:55 PM, Brent Fulgham <bfulgham at apple.com> wrote:
> Coming back to your earlier example:
>     auto newSize = optimalSize();
> vs:
>     CGSize newSize = optimalSize();
> If I understand your argument, you feel that the explicit CGSize
> declaration helps the reader because it makes the return value of
> optimalSize() explicit.

It also clarifies that newSize is, indeed, CGSize.  It's often useful to
clarify the type of a local variable.

However, that declaration is only stating the type that the author *thinks*
> optimalSize() returns.  There is nothing to guarantee that optimalSize()
> returns a CGSize; only that it returns something that the compiler can turn
> into a CGSize through some set of casts.

The code stating CGSize could have been correct at one point, but the
> return type of optimalSize might have been changed to some similar type
> without anyone noticing.

This is why we have the following style guideline:
"Use a constructor to do an implicit conversion when the argument is
reasonably thought of as a type conversion and the type conversion is fast.
Otherwise, use the explicit keyword or a function returning the type. This
only applies to single argument constructors."

Having said that, I can see there could be cases where "auto" is more
appropriate because we want to match the type of whatever function we're
calling e.g. inside a template.

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

More information about the webkit-dev mailing list