Search code examples
c++stdstring

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


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?


Solution

  • 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.)