Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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? 

The first one argues that passing integer as argument, right? Why others passes compilation?I tested on Visual C++ and g++, and I got the same result above. So I believe I miss something defined by standard. What is it?

like image 342
Leo Lai Avatar asked Nov 30 '16 09:11

Leo Lai


1 Answers

The problem is that a literal 0 is a null pointer constant. The compiler doesn't know if you meant:

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

or

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

(better compilers list the options).

The workround (as you have discovered) is to write the append as:

tmp += '\0'; 

(I assume you didn't want the string version - tmp += nullptr; would be UB at runtime.)

like image 71
Martin Bonner supports Monica Avatar answered Oct 08 '22 21:10

Martin Bonner supports Monica