String 是STL裏面的相似一個字符串容器。ios
String對象調用append(),不能之家已有的字符串加大,由於相鄰的內存可能被佔用,所以須要分配一個新的內存塊,將原來的內存賦值到新的內存塊中。這樣會下降效率。c++
因此c++實現分配了一個比實際字符串大的內存塊,若是字符串不斷增大,超過了內存塊大小,程序將分配一個大小爲原理兩倍的新內存卡,以提升足夠的空間。app
#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; }