logoalt Hacker News

wheybagsyesterday at 10:12 AM2 repliesview on HN

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?"


Replies

jcelerieryesterday at 11:40 AM

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

I've seen much more perf-murdering things being caused by

   std::map<std::string, int> my_map;
   for(const std::pair<std::string, int>& v: my_map) {
       ...
   }
than with auto though
show 2 replies
spacechild1yesterday at 10:32 AM

> Yes, you could make the same mistake without auto, but it's easier to notice.

Is it really? I rather think that a missing & is easier to spot with "auto" simply because there is less text to parse for the eye.

> If you see "for (auto v : vec)" looks good right?

For me the missing & sticks out like a sore thumb.

> It's easy to forget (or not notice) that auto will not resolve to a reference in this case

Every feature can be misused if the user forgets how it works. I don't think people suddenly forget how "auto" works, given how ubiquitous it is.

show 1 reply