Can I assign a double line?

According to this page, there are five ways to assign a string to a string:

string (1) string& operator= (const string& str); c-string (2) string& operator= (const char* s); character (3) string& operator= (char c); initializer list (4) string& operator= (initializer_list<char> il); move (5) string& operator= (string&& str) noexcept; 

Then why should I compile the text below? Which of these parameters was used by the compiler?

 #include <iostream> #include <string> int main() { std::string s; double d = 1.0; s = d; std::cout << s << std::endl; } 

And this is not just a pointless question - I spent a lot of time trying to find this s = d destination in my code. Of course, this should be s = std::to_string(d) .

Compiler: GCC 4.8.4.

+6
source share
2 answers

Your code is equivalent to this code:

 #include <iostream> #include <string> int main() { std::string s; double d = 1.0; char j = d; s = j; std::cout << s << std::endl; } 

So you will output \1 followed by the end of the line.

If you are using g ++, specify -Wconversion to catch such things.

f.cpp: In the function 'int main ():
f.cpp: 8: 7: warning: converting to 'char from' double may change its value [-Wfloat-conversion]
s = d;

+7
source

It performs this conversion: double -> char and therefore uses the following overload:

 character (3) string& operator= (char c); 

I tested this by scanning your output with od :

 > ./a.out | od -c 0000000 001 \n 
+4
source

Source: https://habr.com/ru/post/1014886/


All Articles