max({"a", "b", "z", "x"}); returns "x"
while both
max<std::string>({"a", "b", "z", "x"});
and
max({'a', 'b', 'z', 'x'});
return "z" as they should. Why?
"a"
, "b"
etc. are string literals. These decay to const char*
when in the initializer list. max
just probably gets the one with the highest address, but since it uses operator<
to compare them, and they aren't part of the same array, or one-past the same array, the result of the comparison is unspecified (and the invocation of max
would result in undefined behaviour, since the requirement is that the type be LessThanComparable
).
The other two invocations of max
are well defined. char
s such as a
, b
etc. are integral types with a well defined less-than comparison. And std::string
has an operator<
that implements a lexicographical comparison.