std :: string及其自动调整内存大小 [英] std::string and its automatic memory resizing

查看:1306
本文介绍了std :: string及其自动调整内存大小的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对C ++很新,但我知道你不能只是使用内存似的std :: string类似乎让你做。例如:

I'm pretty new to C++, but I know you can't just use memory willy nilly like the std::string class seems to let you do. For instance:

std::string f = "asdf";
f += "fdsa";

字符串类如何处理越来越大?我假设它分配一个默认的内存量,如果需要更多,它 new 是一个更大的内存块,并复制本身。但是,这不是很低效,以至于必须复制整个字符串每次它需要调整大小?我不能真正想到另一种方式可以做(但显然有人做了)。

How does the string class handle getting larger and smaller? I assume it allocates a default amount of memory and if it needs more, it news a larger block of memory and copies itself over to that. But wouldn't that be pretty inefficient to have to copy the whole string every time it needed to resize? I can't really think of another way it could be done (but obviously somebody did).

对于这个问题,所有的stdlib类如vector,queue,stack等是如何处理增长和收缩这么透明?

And for that matter, how do all the stdlib classes like vector, queue, stack, etc handle growing and shrinking so transparently?

推荐答案

通常,有一个加倍的算法。换句话说,当它填充当前缓冲区时,它分配一个大两倍的新缓冲区,然后复制当前数据。这导致比通过单个分配块生长的替代方案更少的分配/复制操作。

Usually, there's a doubling algorithm. In other words, when it fills the current buffer, it allocates a new buffer that's twice as big, and then copies the current data over. This results in fewer allocate/copy operations than the alternative of growing by a single allocation block.

这篇关于std :: string及其自动调整内存大小的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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