字符串如何在c ++中分配内存?

编程入门 行业动态 更新时间:2024-10-22 19:33:16
本文介绍了字符串如何在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 ++中分配内存?

本文发布于:2023-10-27 03:21:46,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1532166.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:字符串   分配   内存   如何在

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!