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

Bem Jones-Bey bjonesbe at adobe.com
Mon Jan 6 14:30:24 PST 2014

On Jan 6, 2014, at 13:49 , Geoffrey Garen <ggaren at apple.com<mailto:ggaren at apple.com>> wrote:

Let me try to clarify with two more motivating examples:

(1) Nodes.cpp:

FunctionParameters::FunctionParameters(ParameterNode* firstParameter, unsigned size)
    : m_size(size)
    unsigned i = 0;
    for (ParameterNode* parameter = firstParameter; parameter; parameter = parameter->nextParam()) {
        auto pattern = parameter->pattern();
        patterns()[i++] = pattern;

If I had to describe this algorithm in English, I’d say, “Collect and retain all the [auto] from the list of parsed parameters.” I think that explanation would be stronger if “[auto]” were a concrete noun.

Does anybody prefer auto in this context? If so, why?

While I wouldn't say that I prefer auto here, it doesn't really bother me in this example. Personally, I would read that as "Collect and retain all of the patterns from the list of parsed parameters", and I'd say it the same way if auto had been an explicit type.

(2) ApplyStyleCommand.cpp:

    auto children = elementChildren(*dummySpanAncestor);
    for (auto child = children.begin(), end = children.end(); child != end; ++child) {
        if (isSpanWithoutAttributesOrUnstyledStyleSpan(&*child))

I don’t understand why we’re &*’ing here. That’s a surprising idiom I haven’t seen before, which I would expect to be a no-op. My first question when reading this is, “What is the type of ‘child’, such that I would need to &* it?”.

Is this "&*child” obvious to everyone else?

It's actually pretty obvious to me, but I've been spending a lot of time with similar iterators lately. I don't think it's that much clearer without the auro. I've definitely found this to be confusing in the codebase much before auto entered the picture. (In this case, I'd argue strongly for using an accessor method on the iterator or a temporary variable)

- Bem

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

More information about the webkit-dev mailing list