To understand more using directives and function overloading I've tried this program:
namespace ns{
void f(int){cout << "int\n";}
void f(double){cout << "double\n";}
void f(std::string){cout << "string\n";}
struct Foo{};
}
void f(ns::Foo const&){
cout << "ns::Foo\n";
}
namespace bin{
void f(int*){
std::cout << "bin::f(int*)\n";
}
}
int main(){
using namespace ns;
//using namespace bin;
f(7); // int
f(7.5); // double
f(ns::Foo{}); // ns::Foo
try{
f(nullptr);
}
catch(std::exception const& e){
std::cout << e.what() << std::endl;
}
}
When I run the program, it works fine, except for the last call to f(nullptr) which causes a runtime error:
int
double
ns::Foo
basic_string::_M_construct null not valid
If I un-comment the using directive for namespace bin, then the code works fine.
using namespace bin;
The output:
int
double
ns::Foo
bin::f(int*)
void f(std::string)will erroneously try and convertchar*tostd::string.f(0). Any other number will be caught by the compiler as an illegal integer-to-string conversion, but the historical relationship betweenNULLand 0 gets in the way here.