字符串如何在c ++中分配内存? [英] How do strings allocate memory in c++?

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

问题描述

我知道动态内存比设置固定大小的数组并使用它的一部分具有优势。但是在动态内存中,您必须输入要存储在阵列中的数据量。使用字符串时,您可以键入任意多个字母(您甚至可以将字符串用于数字,然后使用函数对其进行转换)。这个事实使我认为,与字符串相比,字符数组的动态内存已过时。

I know that dynamic memory has advantages over setting a fixed size array and and using a portion of it. But in dynamic memory you have to enter the amount data that you want to store in the array. When using strings you can type as many letters as you want(you can even use strings for numbers and then use a function to convert them). This fact makes me think that dynamic memory for character arrays is obsolete compared to strings.

所以我想知道使用字符串时的优缺点是什么?何时释放字符串占用的空间?也许可以通过释放优于字符串的优点来释放动态分配的内存?请解释。

So i wanna know what are the advantages and disadvantages when using strings? When is the space occupied by strings freed? Is maybe the option to free your dynamically allocated memory with delete an advantage over strings? Please explain.

推荐答案

std :: string通常包含内部动态分配的缓冲区。当您分配数据时,或者如果您推回新数据,而当前缓冲区大小不足,则会以增加的大小分配新缓冲区,并将旧数据复制或移动到新缓冲区中。然后将旧缓冲区释放。

std::string usually contains an internal dynamically allocated buffer. When you assign data, or if you push back new data, and the current buffer size is not sufficient, a new buffer is allocated with an increased size and the old data is copied or moved to the new buffer. The old buffer is then deallocated.

当字符串超出范围时,将释放主缓冲区。如果字符串对象是函数(在堆栈中)中的局部变量,它将在当前代码块的末尾取消分配。如果是函数参数,则函数退出时。

The main buffer is deallocated when the string goes out of scope. If the string object is a local variable in a function (on the stack), it will deallocate at the end of the current code block. If it's a function parameter, when the function exits. If it's a class member, whenever the class is destroyed.

字符串的优点是灵活性(会自动增加大小)和安全性(很难越过字符串的界限)。数组)。堆栈上固定大小的char数组速度更快,因为不需要动态分配。但是如果您有性能问题,应该担心,而不是之前。

The advantage of strings is flexibility (increases in size automatically) and safety (harder to go over the bounds of an array). A fixed-size char array on the stack is faster as no dynamic allocation is required. But you should worry about that if you have a performance problem, and not before.

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

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