result of memcpy(&x[0], "fsd", 3)
string x;
78 x.reserve(100);
79 x[0] = '1';
80 x[1] = '2';
81 x[2] = '\0';
82 x.resize(3);
83 cout << "sdfs: " << x.c_str() <&l开发者_如何学Ct; endl;
84 cout << &x[0] << endl;
85 return 0
test result: print nothing
std::string
does not necessarily store its data as C strings, i.e. with a \0
appended. Instead, the length of the string is held internally. If you change the contents, that's fine, but resize()
does not know that there is actual data, as the length is still 0 from string
's point of view. Quoting from the docs:
If n is greater than the current length of the string, the content is expanded by appending as many instances of the c character as needed to reach a size of n characters.
The c
character in this call is \0, so resize()
actually changes your string back to the empty one.
This is the correct behavior, as directly modifying the contents of std::string
in this way is not supported. Use operator[]
, append
and so on instead.
78 x.reserve(100);
This just reserves memory for the string. It means that now you can append 100 characters to the string without the string having to reallocate memory.
This does not change the size of the string. x
is still an empty string.
79 x[0] = '1';
80 x[1] = '2';
81 x[2] = '\0';
This is accessing indexes out of bounds (which you can get away with if the implementation does not provide runtime checks, since you have reserved the memory)
82 x.resize(3);
This produces a valid string, 3 characters in length, each character with the default value ('\0'
).
You should take your time to make sure that you do actually ask a question, and also keep the title and the question in sync. As to what might be puzzling you (your code is what puzzles me), std::string::resize()
will fill with '\0' the new elements created, overwriting your previous edit. Move the resize()
over the assignment and you will be fine.
精彩评论