相關資料搜索於 community.csdn.net
在《C++ Primer》的 82 頁有這樣一個例子:
* C 風格字符串實現代碼
*/
#include <iostream>
#include <cstring>
int main() {
int errors=0;
const char *pc="a verry long literal string";
for( int ix = 0; ix < 1000000; ++ix ) {
int len = strlen( pc );
char *pc2 = new char[ len + 1];
strcpy( pc2, pc );
if ( strcmp( pc2, pc ) ) {
++errors;
}
delete []pc2;
}
cout << "C-style character string: "<< errors <<" errors occured. ";
return 0;
}
* C++ 類 string 的實現代碼
*/
#include <iostream>
#include <string>
int main() {
int errors = 0;
sring str( "a verry long literal string" );
for( int ix = 0; ix < 1000000; ++ix ) {
int len = str.size();
string str2 = str;
if ( str != str2 ) {
++errors;
}
}
cout << "string class: "<< errors << " errors occured. ";
return 0;
}
作者在書中提到:“平均來說,string 類型實現的執行速度是 C 風格字符串的兩倍,在一臺 UNIX 機器上,前一個程序(C 風格的)用時 1.98 秒,後一個(C++ 風格的)用時 0.96 秒。
產生此種差異的原因在於 string 類型是 “寫時複製” 的,如果 str2 沒有改變,str2 就沒在真正在內存中構造,而與 str 實例共用一個內存單元。只要在構造後加一句 str2[0]='A',整個程序的運行時間就與 C 風格字符串的實現相當了。