logoalt Hacker News

jcelerieryesterday at 11:40 AM2 repliesview on HN

> 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

Replies

verallyesterday at 5:46 PM

Wow I really thought this would be a compile error. The implicit cast here really is a footgun. Looks like '-Wrange-loop-construct' (included in -Wall) does catch it:

> warning: loop variable 'v' of type 'const std::pair<std::__cxx11::basic_string<char>, int>&' binds to a temporary constructed from type 'std::pair<const std::__cxx11::basic_string<char>, int>' [-Wrange-loop-construct] 11 | for (const std::pair<std::string, int>& v: m) {

As they say, the power of names...

dubi_steinkekyesterday at 1:23 PM

Why is this a perf footgun? As someone who doesn't write a lot of c++, I don't see anything intuitively wrong.

Is it that iterating over map yields something other than `std::pair`, but which can be converted to `std::pair` (with nontrivial cost) and that result is bound by reference?

show 1 reply