在 C++ 标准中std:string
遵循指数增长策略,因此我认为capacity()
连接期间的字符串在必要时总是会增加。但是,当我测试时test.cpp
,我发现在for循环中,只有每两次才会在分配期间capacity()
缩回length()
。
为什么这种行为不取决于字符串的长度,而是取决于我更改字符串的频率?是某种优化吗?
以下代码使用g++ -std=c++11
.
测试.cpp:
#include <iostream>
int main(int argc, char **argv) {
std::string s = "";
for (int i = 1; i <= 1000; i++) {
//s += "*";
s = s + "*";
std::cout << s.length() << " " << s.capacity() << std::endl;
}
return 0;
}
输出将是这样的:
1 1
2 2
3 4
4 4
5 8
6 6 // why is capacity shrunk?
7 12
8 8 // and again?
9 16
10 10 // and again?
11 20
12 12 // and again?
13 24
14 14 // and again?
15 28
16 16 // and again?
17 32
...
996 996
997 1992
998 998 // and again?
999 1996
1000 1000 // and again?