问题
For example:
// is type: std::istream
// str type: std::string
is >> str;
How does this grow str
to accommodate the input? It reads character by character and calls str.push_back()
(or something similar)? Or does it have a mechanism for knowing the input size before reading the input?
I realize that the standard most likely doesn't specify this details, but I am more interested in common implementations (e.g. gcc
).
This question is a curiosity as in C you don't know beforehand how much to allocate for the string (C-style vector of chars of course), but C++ manages that for you.
Please note this is not a question about C++ management of dynamic memory, but about the knowing or not knowing the size of the read input before reading it into the buffer/variable. In that note of course that if str
is big enough already, no reallocation will occur, but that is not the point here.
回答1:
You can find libstdc++'s implementation here.
As you can see, it uses an array of 128 characters as a buffer, and reads characters sequentially into the buffer until either the buffer fills up or it reaches the end of the string to be read. If the buffer fills up, the characters are appended to the string and the buffer is reused. So 128 characters are appended to the string at a time, except possibly during the last append operation. The stream indeed has no way of knowing how many characters will be read in advance. The string's memory allocation strategy is not coupled with the stream.
来源:https://stackoverflow.com/questions/27763488/c-how-do-streams-allocate-space-for-input