Consider the following code snippet:
#include <iostream>
int main() {
std::string foo;
foo = -1; // why is the compiler not complaining about this?
std::cout << "1" << std::endl;
std::cout << foo << std::endl;
std::cout << "2" << std::endl;
}
Actual output (both ideone.com C++14 mode and GCC 4.8.4):
<no output>
Questions:
foo = -1
, I get the correct stdout (1
and 2
). What has the compiler compiled with foo = -1;
that causes the subsequent cout
s to fail?std::string::assign() in C++ The member function assign() is used for the assignments, it assigns a new value to the string, replacing its current contents. Syntax 1: Assign the value of string str.
The std::string class manages the underlying storage for you, storing your strings in a contiguous manner. You can get access to this underlying buffer using the c_str() member function, which will return a pointer to null-terminated char array. This allows std::string to interoperate with C-string APIs.
foo = -1;
resolves to std::string::operator=(char)
since -1
is an int
and int
can, in theory, be converted to a char
.
It's not clear to me what the standard says when the int
does not represent a valid char
. It looks like in your implementation, the program crashes.
Update
From the C++11 Standard (emphasis mine):
3.9.1 Fundamental types
1 Objects declared as characters (
char
) shall be large enough to store any member of the implementation’s basic character set. If a character from this set is stored in a character object, the integral value of that character object is equal to the value of the single character literal form of that character. It is implementation-defined whether a char object can hold negative values.
It appears that you'll have to consult your compiler's documentation to understand whether it allows char
object to hold negative values and, if it does, how does it treat such objects.
char
is an integral type in C++. std::string
defines an assignment operator:
std::string& operator=(char);
Since int
converts to char
freely in this context, no diagnostic is given. (It's funny how best intentions pave the road to Hell, innit?)
Since (char)-1
is probably not a valid member if the execution character set on your platform, the stream enters an error state and will stay there, outputting nothing, until the error bit is cleared.
EDIT this is a bug of ideone. If the output stream contains an "illegal" character, the entire stream is not shown, even the parts produced and flushed before the bad character. Use another online compiler to check.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With