为什么在将char添加到空字符串时返回未知值(如""+ c)?

Joe*_*Joe 5 c++ string char

请允许我先向您展示我的代码:

void testStringAdd(){
   char c = '$';
   string str = "";
   str += c;//the same as `str = str + c;`
   cout << str << "---";
   cout << "size : " << str.size() << endl;
   str = "" + c;//the same as `str = c + ""`;
   cout << str << "---";
   cout << "size : "<< str.size() << endl;
}
Run Code Online (Sandbox Code Playgroud)

我预计输出是:

$ ---尺寸:1

$ ---尺寸:1

但vs2013的实际输出是:

$ ---尺寸:1

---大小:0

这是一个有趣的现象,我想知道它为何如此奇怪?

注意:如果我编码string str = "";然后str == ""将返回true.

son*_*yao 9

In str = "" + c;,""不是std::string,它是一个带有类型的字符串文字const char[],然后衰减到const char*"" + c成为指针算术.

在这种情况下,由于c具有正值,"" + c将导致UB,这意味着一切皆有可能.对你来说,程序不会崩溃可能是幸运的(或不幸的).

正如评论所指出的那样,明确转换std::string将解决问题.

str = std::string("") + c;
Run Code Online (Sandbox Code Playgroud)

或者使用std :: string文字运算符(从C++ 14开始):

str = ""s + c;
Run Code Online (Sandbox Code Playgroud)

  • 不会`str = std :: string("")+ c;`修复问题? (2认同)