如何存储C ++字符串? [英] How are C++ strings stored?

查看:226
本文介绍了如何存储C ++字符串?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


可能重复:

std :: string及其自动调整内存大小

我只是好奇,如何将字符串存储在内存中?例如,当我这样做:

I am just curious, how are strings stored in memory? for example, when I do this:

string testString = "asd";

它分配4个字节,对吧? a + s + d + \0

it allocates 4 bytes, right? a + s + d + \0.

但后来,当我想为这个字符串分配一些新的文本时,它可以正常工作,但我不明白如何。例如,我这样做:

But later, when I want to assign some new text to this string, it works, but I don't understand how. For example I do this:

testString = "123456789"

现在它应该是10个字节长。但是如果没有空间这样的字符串怎么办?让我们说从字符串开始的第五+第六个字节由一些其他2个字符。 CPU如何处理?

Now it should be 10 bytes long. But what if there wasn't space for such string? let's say that fifth+sixth bytes from the beginning of string are taken by some other 2 chars. How does the CPU handles it? It finds completely new position in memory where that string fits?

推荐答案

这是与实现相关的,但是一般的想法是字符串类将包含指向存储字符串实际内容的内存区域的指针。两个常见的实现是存储3个指针(分配的区域和数据的开始,数据的结束,分配区域的结束)或指针(分配的区域和数据的开始)和两个整数(字符串中的字符数和分配的数目字节)。

This is implementation dependent, but the general idea is that the string class will contain a pointer to a region of memory where the actual contents of the string are stored. Two common implementations are storing 3 pointers (begin of the allocated region and data, end of data, end of allocated region) or a pointer (begin of allocated region and data) and two integers (number of characters in the string and number of allocated bytes).

当新数据附加到字符串时,如果它适合分配的区域,它将被写入,并且数据指针的大小/结束将被相应地更新。如果数据不适合该区域,将创建一个新的缓冲区并复制数据。

When new data is appended to the string, if it fits the allocated region it will just be written and the size/end of data pointer will be updated accordingly. If the data does not fit in the region a new buffer will be created and the data copied.

还要注意,许多实现都对小字符串进行了优化,其中字符串类确实包含一个小缓冲区。如果字符串的内容适合缓冲区,则不会动态分配内存,只使用本地缓冲区。

Also note that many implementations have optimizations for small strings, where the string class does contain a small buffer. If the contents of the string fit in the buffer, then no memory is dynamically allocated and only the local buffer is used.

这篇关于如何存储C ++字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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