C风格字符串和C++的标准库类型string的比较

来源:互联网 发布:吐槽大会 王刚 知乎 编辑:程序博客网 时间:2024/05/22 03:40

以下两段程序反映了使用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)

        ;

}

原创粉丝点击