Why is this compiling: string = int

Assume 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 string str = func(); compiles without warning about type mismatch?

I am using the gcc v compiler. 4.7.1 with the -std = C ++ 11 flag set.

Output:

Acquired value: ''

+6
source share
1 answer

The std::string includes an overloaded operator= , which takes a char value. Since char is an integer type, int implicitly converted to char .

The value assigned to str is not an empty string; it is a string of length 1, in which one character has a value of 2 (Ctrl-B).

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

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

All Articles