C++ How do streams allocate space for input?

佐手、 提交于 2021-01-28 03:18:16

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!