thomas.g...@gmail.com writes:
> Why exactly does the following code compile?
> I would expect that it is not possible to cast (?) 0 to some const reference.
I agree with the "?": I would not use the word cast here. A cast is an
operator used to perform explicit conversions, and there is no cast
operator in the code.
What's more, the part you are asking about is not really a type
conversion at all; instead, a temporary std::string object is being
created.
> What is the C++ language rule behind this?
One of the constructors for std::string has a single const char *
parameter, and the literal 0 is a valid argument for that constructor.
There are lots of language rules that are needed to explain the gory
details but this might be enough explanation for now.
<snip>
> #include <string>
> void f(const std::string &) {}
> int main() {
> f(0);
> }
Calling this std::string constructor with a null pointer as the argument
is undefined behaviour, so the code might compile but it's not valid.
--
Ben.