String 是STL里面的類似一個字符串容器。
String對象調用append(),不能之家已有的字符串加大,因為相鄰的內存可能被占用,因此需要分配一個新的內存塊,將原來的內存賦值到新的內存塊中。這樣會降低效率。
所以c++實現分配了一個比實際字符串大的內存塊,如果字符串不斷增大,超過了內存塊大小,程序將分配一個大小為原理兩倍的新內存卡,以提高足夠的空間。
#include <iostream> #include <string> int main() { using namespace std; string empty; string small = "bit"; string large = "Elephants are a girl's best friend"; cout << "Sizes:"<<endl; cout << "\tempty: "<< empty.size()<<endl; cout << "\tsmall: "<< small.size()<<endl; cout << "\tlarge: "<< large.size()<<endl; //重新分配內存大小 cout << "Capactities: \n"; cout << "\tempty: "<< empty.capacity()<<endl; cout << "\tsmall: "<< small.capacity()<<endl; cout << "\tlarge: "<< large.capacity()<<endl; //reserve方法能夠請求內存塊的最小長度 empty.reserve(50); cout << "Capacity after empty.reserve(50): " << empty.capacity() << endl; return 0; }