logoalt Hacker News

physicsguyyesterday at 8:42 AM1 replyview on HN

Auto is fine where the context is obvious, I think. For e.g.:

    void func(std::vector<double> vec) {
        for (auto &v : vec) {
            // do stuff
        }
    }

Here it's obvious that v is of type double.

Replies

wheybagsyesterday at 10:12 AM

v is double& in your example, not double. But it's not obvious that omitting the & causes a copy. If you see "for (auto v : vec)" looks good right? But if vec contains eg long strings, you've now murdered your perf because you're copying them out of the array instead of grabbing refs. Yes, you could make the same mistake without auto, but it's easier to notice. It's easy to forget (or not notice) that auto will not resolve to a reference in this case, because using a reference is "obviously what I want here", and the name of the feature is "auto" after all - "surely it will figure it out, right?"

show 2 replies