c++ - std::string 是否保证不会自发归还内存?

标签 c++ language-lawyer heap-memory stdstring

如果从较小大小的字符串重新分配,std::string 不会自发归还分配的内存,标准是否保证?

换句话说:

std::string str = "Some quite long string, which needs a lot of memory";
str = "";
str = "A new quite long but smaller string"; // Guaranteed to not result in a heap allocation?

我问是因为我依靠这个来避免堆碎片。

最佳答案

没有任何保证。

[string.cons]/36定义了将 const char* 分配给 std::string 的移动赋值,其定义是:

[string.cons]/32

basic_string& operator=(basic_string&& str)  noexcept(/*...*/)

Effects: Move assigns as a sequence container, except that iterators, pointers and references may be invalidated.

这表明委员会让实现在无效操作和更保守的操作之间自由选择。为了让事情更清楚:

[basic.string]/4

References, pointers, and iterators referring to the elements of a basic_­string sequence may be invalidated by the following uses of that basic_­string object:

  • (4.1) as an argument to any standard library function taking a reference to non-const basic_­string as an argument.
  • (4.2) Calling non-const member functions, except operator[], at, data, front, back, begin, rbegin, end, and rend.

I ask because i'm depending on this to avoid heap fragmentation.

std::string 将分配器作为模板参数。如果您真的担心可能的堆碎片,您可以编写自己的,通过一些启发式方法可以有适合您需求的分配策略。

在实践中,我所知道的大多数实现都不会在您提出问题的情况下重新分配内存。这可以通过测试和/或检查您的实现文档以及最终的源代码来检查。

关于c++ - std::string 是否保证不会自发归还内存?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52495704/

相关文章:

c++ - GMP、C语言内存分配和指针

c++ - 是否有任何静态分析工具可以帮助检测 shared_ptr<> 循环引用?

c++ - "Reading"POD 预增量结果不会产生未定义的行为。为什么呢?

android - 如何修复我的 android 照片上传以发送更大的数据流

c++ - 如何将 spec256k1 编译成共享对象?

c++ - 无法添加二维数组的列和行

c++ - 初始化一个零数组

c++ - 静态存储持续时间初始化

go - gc 会在 Golang 中将数组设置为 nil 时收集对象吗?

c - 通过复制返回一个结构,它封装了一个指针