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

Filip Pizlo fpizlo at apple.com
Thu Jan 2 15:02:46 PST 2014


On Jan 2, 2014, at 2:55 PM, Brent Fulgham <bfulgham at apple.com> wrote:

> Hi Filip,
> 
> 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.
> 
> 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.

Yes, C++ offers some interesting escape hatches from the type-system so this documentation (i.e. the use of "CGSize" to ascribe a type to newSize) needs to be interpreted carefully.  It's not guaranteeing that optimalSize() returns a CGSize, only that it returns something that is coercible to a CGSize.  Also, it does guarantee that newSize is indeed a CGSize and not anything else.

To me, that's still better than no information at all, which is what "auto" does.

> 
> 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.
> 
> Using ‘auto’ doesn’t seem to make this situation any worse.

It conveys zero information, whereas declaring the variable as CGSize does convey meaningful information about optimalSize(), newSize, and the kinds of things you could do with newSize.

> 
> In fact, although Sutter’s suggestion of:
> 
> 	auto newSize = CGSize { optimalSize(); }
> 
> looks gross to my eye, it might be a useful approach because it would force the compiler to complain if we were returning something that was not explicitely a CGSize type.

I know this doesn't apply to CGSize, but the approach we've been using in JSC is to make all unary constructors 'explicit' and to prefer wrapper classes over typedefs, even for primitive values.  This also has the effect of preventing many implicit coercions, and it carries some other benefits also:

1) It means that you don't have to use this gross syntax.

2) It controls the kind of coercions that can happen even in cases where there is no variable, like setSize(optimalSize()).

-Filip


> 
> -Brent

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


More information about the webkit-dev mailing list