Write your question here.
Why am I allowed to pass nullptr to a function that expects a string, but not allowed to compare the string against a nullptr ?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
#include <iostream>
#include <fstream>
#include <string>
#include <cstdlib>
void f(std::string s)
{
if (s != nullptr)
std::cout << s.size();
}
int main()
{
f(nullptr);
system("pause");
return 0;
}
Error msg in VS 2015:
Error C2678 binary '!=': no operator found which takes a left-hand operand of type 'std::string'(or there is no acceptable conversion) in main.cpp 8
I think you are seeing polymorphism. String accepts char * in its constructor and I think from assignments, and it may see null as a null char* here.
In that case the length of the string is zero.
You can't compare string and char * directly, you need to either promote to strings to use overloaded comparisons or use strcmp on the underlying char* in the string which you can get at if needed. Because of that, you can't check for null pointer on the string though --- you can check the underlying char* but I don't think that will BE null in the string.
I think you are seeing polymorphism. String accepts char * in its constructor and I think from assignments, and it may see null as a null char* here.
No what you're seeing is undefined behavior. The C++ standard specifically forbids a nullptr as the first argument to the std::string constructor.
You can't compare string and char * directly
Yes you can.
The problem really has nothing to do with a char* since you're not trying to compare the std::string to a char*, you're trying to compare a std::string to a nullptr. Remember a nullptr is a type of it's own. The compiler doesn't know how to compare a nullptr to a std::string. A std::string can never be a nullptr.
By the way, after removing the if() statement the program compiles for me, but the program throws an exception when run when the compiler tries to make a copy of the std::string.