std :: string =操作员不能将0作为参数传递

std::string += operator cannot pass 0 as argument

本文关键字:参数传递 不能 string 操作员 std      更新时间:2023-10-16
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 += '';//ok...expected
tmp +=INT_MAX;//ok
tmp +=int(INT_MAX);//still ok...what?

第一个人认为将整数作为参数,对吗?为什么其他人通过汇编?我在Visual C 和G 上进行了测试,而我在上面得到了相同的结果。因此,我相信我想念标准定义的东西。是什么?

问题是文字0是 null指针常数。编译器不知道您的意思是:

std::string::operator +=(const char*);  // tmp += "abc";

std::string::operator +=(char);         // tmp += 'a';

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

工作扳机(如您所发现的)是将附加写为:

tmp += '';

(我认为您不想要字符串版本-tmp += nullptr;在运行时是UB。)

0文字可隐式转换为所有指针类型(导致其各自的空指针常数)。因此,它导致两个同样有效的转换序列,以匹配std::string S附录操作员。