Why does C++ allow an integer to be assigned to a string?

冷暖自知 提交于 2019-11-26 06:43:33

问题


I encountered an interesting situation today in a program where I inadvertantly assigned an unsigned integer to a std::string. The VisualStudio C++ compiler did not give any warnings or errors about it, but I happened to notice the bug when I ran the project and it gave me junk characters for my string.

This is kind of what the code looked like:

std::string my_string(\"\");
unsigned int my_number = 1234;
my_string = my_number;

The following code also compiles fine:

std::string my_string(\"\");
unsigned int my_number = 1234;
my_string.operator=(my_number);

The following results in an error:

unsigned int my_number = 1234;
std::string my_string(my_number);

What is going on? How come the compiler will stop the build with the last code block, but let the first 2 code blocks build?


回答1:


Because string is assignable from char, and int is implicitly convertible to char.




回答2:


The std::string class has the following assignment operator defined:

string& operator=( char ch );

This operator is invoked by implicit conversion of unsigned int to char.

In your third case, you are using an explicit constructor to instantiate a std::string, none of the available constructors can accept an unsigned int, or use implicit conversion from unsigned int:

string();
string( const string& s );
string( size_type length, const char& ch );
string( const char* str );
string( const char* str, size_type length );
string( const string& str, size_type index, size_type length );
string( input_iterator start, input_iterator end );



回答3:


It is definitely operator=(char ch) call - my debugger stepped into that. And my MS VS 2005 compiles following without error.

std::string my_string("");
unsigned int my_number = 1234;
my_string = my_number;
my_string.operator=(my_number);



回答4:


I can explain the first and third situations:

my_string = 1234;

This works because string has overridden operator=(char). You are actually assigning a character (with data overflow) into the string. I don't know why the second case results in a compile error. I tried the code with GCC and it does compile.

std::string my_string(1234);

will not work, because there is no string constructor that takes a char or int argument.



来源:https://stackoverflow.com/questions/1177704/why-does-c-allow-an-integer-to-be-assigned-to-a-string

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!