[Bug libstdc++/92300] Useless allocator call in std::map, when insert does not perform any insertion.
redi at gcc dot gnu.org
gcc-bugzilla@gcc.gnu.org
Fri Dec 3 22:48:02 GMT 2021
https://gcc.gnu.org/bugzilla/show_bug.cgi?id=92300
--- Comment #4 from Jonathan Wakely <redi at gcc dot gnu.org> ---
(In reply to Jonathan Wakely from comment #3)
> This inserts the correct value type, and doesn't perform an addition
> allocation:
>
> assert(a.insert(std::pair<const int, int>(1, 1)).second);
> assert(a.insert(std::pair<const int, int>(2, 2)).second);
> assert(!a.insert(std::pair<const int, int>(1, 3)).second);
Or simply a.insert({1, 1}) which calls the same overload as those lines above.
Basically the problem is that you are using make_pair when it isn't only
unnecessary, it's actively harmful. There are much better solutions in modern
C++.
However, there are other scenarios where this optimization would be useful,
where you already have a pair from some other source (rather than creating it
incorrectly at the point of insertion).
More information about the Gcc-bugs
mailing list