Hacker News new | ask | show | jobs
by cousin_it 3432 days ago
So first of all, max("a", "b") expands to max<const char*>("a", "b"). It computes the maximum of two pointers, without looking at the characters at all. Comparing two pointers to unrelated objects is unspecified behavior, but in this case it usually returns the second pointer.

As for max<string>("a", "b"), it implicitly converts both arguments into temporary strings, then returns a const reference to one of them. Since it's a reference to a temporary, it becomes dangling when max returns, but you can assign it to a const string& anyway. When you try to access it, you'll get garbage or crash.

1 comments

Thank you for the explanation! I'll have to look out for that one...