C++ 標準std:string
では、指数関数的な成長ポリシーに従っているため、capacity()
連結中の文字列は必要に応じて常に増加すると思います。ただし、テストtest.cpp
したところ、for ループでは、代入中に2 回ごとcapacity()
に縮小されることがわかりました。length()
この動作が文字列の長さに依存するのではなく、文字列を変更する頻度に依存するのはなぜですか? ある種の最適化ですか?
次のコードは でテストされていg++ -std=c++11
ます。
test.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?