C ++流如何为输入分配空间? [英] C++ How do streams allocate space for input?

查看:70
本文介绍了C ++流如何为输入分配空间?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

例如:

// is  type: std::istream
// str type: std::string
is >> str;

它如何增长 str 以适应输入?它逐个字符地读取并调用 str.push_back()(或类似方法)?还是有一种在读取输入之前就知道输入大小的机制?

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?

我意识到该标准很可能未指定此详细信息,但我对常见的实现方式(例如 gcc )更感兴趣.

I realize that the standard most likely doesn't specify this details, but I am more interested in common implementations (e.g. gcc).

这个问题是一个好奇,因为在C语言中,您事先不知道要为字符串分配多少(当然,是char的C样式向量),但是C ++会为您管理.

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.

请注意,这不是关于动态内存的C ++管理的问题,而是关于在将读取的输入读入缓冲区/变量之前了解或不了解读取的输入的问题.当然,在该注释中,如果 str 已经足够大,则不会发生重新分配,但这不是重点.

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.

推荐答案

您可以找到libstdc ++的实现此处.

You can find libstdc++'s implementation here.

如您所见,它使用128个字符的数组作为缓冲区,并顺序地将字符读入缓冲区,直到缓冲区填满或到达要读取的字符串末尾为止.如果缓冲区已满,则将字符附加到字符串,然后重新使用缓冲区.因此,一次可能会将128个字符追加到字符串中,最后一次追加操作可能除外.实际上,流实际上无法知道将要预先读取多少个字符.字符串的内存分配策略未与流耦合.

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.

这篇关于C ++流如何为输入分配空间?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆