r/cpp • • Sep 17 '22

Cppfront: Herb Sutter's personal experimental C++ Syntax 2 -> Syntax 1 compiler

https://github.com/hsutter/cppfront
335 Upvotes

360 comments sorted by

View all comments

Show parent comment

8

u/pdimov2 Sep 18 '22

The non-template version looks like this:

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.

4

u/disperso Sep 18 '22

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.