Reputation: 398
This is my test case (note the WTF comment):
TEST(string_assignment)
{
std::string str;
std::string cheese="Cheese";
str=cheese;
CHECK_EQUAL(cheese, str);
long lval=0;
str=lval; //WTF - why does the compiler allow this ?
str="";
str.append(cheese);
CHECK_EQUAL(cheese, str);
}
I want to catch instances of std::string being assigned something other than another string or a char*. I had assumed that the compiler would reject the incompatible type but it is allowing it.
How can I tell gcc (version 4.4.3) to reject this silliness ? ... or is there some other way to force rejection of these incompatible types being assigned to std::string ?
Upvotes: 2
Views: 239
Reputation: 361772
It compiles because of the following overload:
string& operator=(char)
Use g++ -Wconversion
in order to print warning messages.
And g++ -Wconversion -Werror
to treat warning as error.
Upvotes: 3
Reputation: 272772
The reason is that the following overload exists:
string &operator=(char)
The compiler can satisfy your assignment with a single implicit conversion, so it compiles.
I think the -Wconversion
GCC flag is supposed to deal with this, but it doesn't seem to work, at least in GCC 4.1.2.
Upvotes: 5
Reputation: 154047
Because it can't. Ultimately, because of C compatibility: a long
, like all other built-in numeric types, converts implicitly to a char
. So in order to ban this, you'd also have to forbid someString = someChar
. Which wouldn't bother me too much, but for whatever reasons, the committee felt was necessary.
Upvotes: 3