To my knowledge a reference cannot be null, but when I run code like this:
#include <iostream>
#include <string>
void test(int i, const std::string& s = nullptr) {
std::cout << i << " " << s << std::endl;
}
int main() {
test(1, "test");
test(2);
}
the optional parameter s
can be null, and the code is built. What's more, when test(2)
runs, the program throws exceptions instead of printing some random strings.
When I changed s
to some basic type like int, it failed to compile, so I think the magic stays inside the string class, but how?
And what's more, how can I check if s
is null or not? if I using if(s==nullptr)
or if(s.empty())
, it fails to compile.