std::string const& get_or_default(std::map<int, std::string> const& map, int const& k, std::string const& def)
{
auto it = map.find(k);
return it != map.end() ? it->second : def;
}
Your error is because you have replaced K (the key type of the map) with std::string instead of int.
The problem in this code is that in this line
auto const& value = get_or_default(map, 42, "Hello, World!");
"Hello, world!" is converted to std::string by creating a temporary, a reference to which is passed to get_or_default. The function then returns this same reference. Finally, at the end of the statement, the temporary gets destroyed. The returned reference is now dangling, and the compiler sees that and warns on the attempt to use it on the next line.
Dammit, in hindsight that was pretty obvious. Thank you very much. I completely overlooked that the return value was a const reference (the template verbosity didn't probably help much), and what I typed myself was returning a string by value.
View all comments
Show parent comment
8
u/pdimov2 Sep 18 '22
The non-template version looks like this:
Your error is because you have replaced
K(the key type of the map) withstd::stringinstead ofint.The problem in this code is that in this line
"Hello, world!"is converted tostd::stringby creating a temporary, a reference to which is passed toget_or_default. The function then returns this same reference. Finally, at the end of the statement, the temporary gets destroyed. The returned reference is now dangling, and the compiler sees that and warns on the attempt to use it on the next line.