如果从较小大小的字符串重新分配,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
, andrend
.
I ask because i'm depending on this to avoid heap fragmentation.
std::string
将分配器作为模板参数。如果您真的担心可能的堆碎片,您可以编写自己的,通过一些启发式方法可以有适合您需求的分配策略。
在实践中,我所知道的大多数实现都不会在您提出问题的情况下重新分配内存。这可以通过测试和/或检查您的实现文档以及最终的源代码来检查。
关于c++ - std::string 是否保证不会自发归还内存?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52495704/