std :: string + =运算符不能传递0作为参数

Leo*_*Lai 37 c++ stdstring

std::string tmp;
tmp +=0;//compile error:ambiguous overload for 'operator+=' (operand types are 'std::__cxx11::string {aka std::__cxx11::basic_string<char>}' and 'int')
tmp +=1;//ok
tmp += '\0';//ok...expected
tmp +=INT_MAX;//ok
tmp +=int(INT_MAX);//still ok...what?
Run Code Online (Sandbox Code Playgroud)

第一个认为传递整数作为参数,对吗?为什么其他人通过编译?我在Visual C++和g ++上测试过,我得到了相同的结果.所以我相信我会错过标准定义的东西.它是什么?

Mar*_*ica 47

问题是文字0是空指针常量.编译器不知道你的意思是:

std::string::operator +=(const char*);  // tmp += "abc";
Run Code Online (Sandbox Code Playgroud)

要么

std::string::operator +=(char);         // tmp += 'a';
Run Code Online (Sandbox Code Playgroud)

(更好的编译器列出选项).

workround(正如您所发现的)是将附加内容写为:

tmp += '\0';
Run Code Online (Sandbox Code Playgroud)

(我假设您不想要字符串版本 - tmp += nullptr;在运行时将是UB.)

  • 是.`char`是一个整数类型,整数可以隐式转换为char.`+ =(char)`是在*all*非模糊情况下调用的重载. (12认同)

Sto*_*ica 11

0文字是隐式转换为所有指针类型(导致它们各自的空指针的常量).因此,它产生两个同等有效的转换序列,用于匹配std::strings附加运算符.