问题
I was working on one my projects, and while I was making the constructor for a class, I was setting some of my variables to a default value. I went to set an std::string to NULL, and it gave me an error. But when I define an std::string and set it to NULL on the same line, it works without any errors. I was wondering why
First Example
std::string text = NULL;
worked, and
Second Example
std::string text;
text = NULL;
didn't work. Now I know you shouldn't set a string to NULL, or 0, but I found this on accident.
Does the first example call a constructor that takes a char*, and thinking that 0 is a pointer to a char? I thought = called a constructor too, so I don't get why they wouldn't both work, unless std::string specifically overloads the = operator.
I am using Microsoft Visual Studio Express 2013
回答1:
Value of NULL evaluates to 0.
Now, std::string text = NULL; will call constructor taking const char* and try to copy the data, but since NULL doesn't point to anything, an error will occur at run-time, I am getting (with gcc 5.2) :
terminate called after throwing an instance of 'std::logic_error'
what(): basic_string::_M_construct null not valid
Since, there is no operator= defined for std::string and int(or size_t), text = NULL; will not compile.
来源:https://stackoverflow.com/questions/33706112/setting-stdstring-to-0-during-definition-vs-setting-stdstring-to-0