I'm trying to understand what std::string::size() returns.
According to https://en.cppreference.com/w/cpp/string/basic_string/size it's the "number of CharT elements in the string", but I'm not sure how that relates to the number of printed characters, especially if string termination characters are involved somehow.
This code
int main() { std::string str0 = "foo" "\0" "bar"; cout << str0 << endl; cout << str0.size() << endl; std::string str1 = "foo0bar"; str1[3] = '\0'; cout << str1 << endl; cout << str1.size() << endl; return 0; } prints
foo 3 foobar 7 - In the case of
str0, the size matches the number of printed characters. I assume the constructor iterates on the characters of the string literal until it reaches\0, which is why only 'f', 'o' and 'o' are put in thestd::string, i.e. 3 characters, and the string termination character is not put in thestd::string. - In the case of
str1, the size doesn't match the number of printed characters. I assume the same went on as what I described above, but that I broke something by assigning a character. According to cppreference.com, "the behavior is undefined if this character is modified to any value other thanCharT()", so I assume I've walked into undefined behavior here.
My question is this: outside of undefined behavior, is it possible that the size of a std::string doesn't match the number of printed characters, or is it actually something guaranteed by the standard?
(note: if the answer to that question changed between versions of the standard I'm interested in knowing that too)
According to https://en.cppreference.com/w/cpp/string/basic_string/operator_at, the behavior is undefined if this character is modified to any value other than CharT(), so I assume I've walked into undefined behavior here.Why?'\0'is a valid CharT in your case.is it possible that the size of a std::string doesn't match the number of printed characterssize returns the number ofCharTs in your string, it has nothing to do with whether they are printable or not. Strings can contain binary data.std::string str0 = "foo" "\0" "bar";is equivalent tostd::string str0 = "foo";Probably you wanted to construct it like thisstd::string str0 ("foo\0bar", 7);?std::string str0("foo\0bar"s)is enough. See How do you construct a std::string with an embedded null?string_literalsnamespace.CharT(), i.e. specifically the default value for CharT, and I assumed it was something other than\0