Setting std::string to 0 during definition vs setting std::string to 0

帅比萌擦擦* 提交于 2019-12-24 15:54:45

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!