Ambiguous integer assignment to C ++ string
So, while playing with C ++, I did this:
#include <iostream>
int main() {
std::string s{"someThing"};
std::cout << " s is: " << s << '\n';
s = 97;
std::cout << " s is: " << s << '\n';
return 0;
}
And when I compiled this with g ++, it compiled fine , and when I run it the output is:
s is: someThing
s is: a
but my doubt is why is this compiled correctly?
Then I found this SO question that addresses this:
Why does C ++ allow an integer to be assigned to a string?
Then I found this from the C ++ doc:
basic_string& operator=( CharT ch );
So my main questions are:
-
Shouldn't it
basic_string& operator=( CharT ch );
be explicit ? That is, why is it alloweds = 97
?s
- this is a string, why should an integer be assigned to it by an implicit conversion? -
Can implicit conversion be avoided / stopped
s = 97
?
And some side questions: this code compiled fine with g ++, but not with clang, which reported this error:
error: expected ';' at end of declaration
std::string s{"someThing"};
^
So why can g ++ compile this and clang cannot?
Edit: Thanks to Edgar Rokyan, it now compiles with clang ++ with an option -std=c++11
.
Edit: So, from the answers by Edgar Rokyan and MSalters,, assignment operator can't be made explicit
okay , but why assign an integer to a valid string ?
source to share
Shouldn't you express
basic_string& operator=( CharT ch );
? That is, why is it:s = 97
allowed?s
is a string, why is an integer assigned to it by an implicit conversion?
From an explicit specifier :
An explicit specifier indicates that a constructor or function conversion (since C ++ 11) does not allow implicit conversions or copy initialization. It may appear only in the specifier-seq declaration of such a function within its class definition.
So, you cannot make the assignment operator explicit.
Can implicit conversion be avoided / stopped
s = 97
?
Generally speaking, no, because it is perfectly legal for std :: string. When you call:
basic_string& operator=( CharT ch );
c 97
, then 97
, which is of type int, is converted to char
and the = operator is executed.
So why does g ++ allow this to be compiled while clang doesn't?
You are most likely trying to compile your program with clang without C ++ 11 support.
source to share