c++ - std::string 和 const char *

标签 c++ string memory-management

如果我用

const char * str = "Hello";

运行时不需要内存分配/释放

如果我用

const std::string str = "Hello";

是否会在字符串类中通过 new/malloc 进行分配?我可以在汇编中找到它,但我不擅长阅读它。

如果答案是“是的,会有 malloc/new”,为什么?如果我需要编辑编辑字符串,为什么只能传递到 std::string 内部的内部 const char 指针并进行实际内存分配?

最佳答案

will be there an allocation via new/malloc inside string class or not?

这取决于。 string 对象必须提供一些内存来存储数据,因为那是它的工作。一些实现使用“小字符串优化”,其中对象包含一个小缓冲区,并且仅在字符串太大时才从堆中分配。

Why can there be only pass through to inner const char pointer inside std::string and do actual memory allocation if I need to edit edit string?

您所描述的不一定是优化(因为每当您修改字符串时它都需要额外的运行时检查),并且在任何情况下都不允许迭代器失效规则。

有人提议 string_view ,允许您使用类似 const string 的接口(interface)访问现有字符序列,而无需任何内存管理。它还不是标准的,并且不允许您修改字符串。

关于c++ - std::string 和 const char *,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28784256/

相关文章:

c++ - 如何在将测试 exe 与 gradle 链接时排除第二个主程序?

c - 函数内的静态变量

Python-字符串分割

c++ - 是否可以使 std::string 始终包含小写字符串?

PHP:变量为字符串时出现 "Array to string conversion"错误

c - 在单个字中存储整数和位

java - Android Activity 内存管理

c++ - 在 union 中使用字符数组

c++ - 如何将 int 转换为 ASCII char C++

c++ - Eigen - 检查矩阵是否为正(半)定