以下两段程序反映了使用C风格字符串与C++的标准库类型string的不同之处。
使用string类型的版本更短,更容易理解,而且出错的可能性更小:
//C-style character string implementation
const char *pc = "a very long literal string";
const size_t len = strlen(pc);
//performance test on string allocation and copy
for(size_t ix = 0;ix!=1000000;++ix){
char *pc = new char [len+1];
strcpy(pc2,pc);
if(strcmp(pc2,pc))
;
delete [] pc2;
}
// string implementation
string str("a very long literal string");
//performance test on string allocation and copy
for(int ix=0;ix!=1000000;++ix){
string str2 = str; //do the copy,automatically allocated
if(str !=str2)
;
}