Search code examples
c++c++11gccstdstring

Why does this compile: string = int


Suppose the following code:

#include <iostream>
#include <string>

int func() { return 2; }

int main()
{
   std::string str("str");
   str = func();
   std::cout << "Acquired value: '" << str << "'" << std::endl;

   return 0;
}

Why does the line str = func(); compile without warning of a type mismatch?

I'm using compiler gcc v. 4.7.1 with the -std=c++11 flag set.

Output:

Acquired value: ''


Solution

  • The std::string class includes an overloaded operator= that accepts a char value. Since char is an integer type, int is implicitly convertible to char.

    The value being assigned to str isn't an empty string; it's a string of length 1 whose single character has the value 2 (Ctrl-B).

    Try feeding your program's output to cat -v or hexdump.

    $ ./c | cat -v
    Acquired value: '^B'