Effective STL 学习笔记: 多用 vector & string

Effective STL 学习笔记: 多用 vector & string

如果可能的话, 尽量避免自己去写动态分配的数组,转而使用 vector 和 string 。

原书作者唯一想到的一个不用 string 的可能的理由,就是 string 所使用的引用计数 (reference counting) 在多线程下可能会因为并发控制反而导致性能下降。我们可以通过查看文档或者 STL 源面的方法来看 String 是否引入了引用计数,如果 string 在多线程下真的因为引用计数而导致了性能下降,我们可以通过下面的方法来避免:

  1. 看是否可以通过某些方法来禁用引用计数,例如条件编译
    该方法可移植性不佳,但最简单。
  2. 看是否有 string 的非引用计数替代品。
  3. vector<char> 来替代 string
    虽然这样可能会导致很多 string 专属的成员函数不能用,但大多的函数都可以通过 STL 算法来替代。
#include <vector>
#include <stdio.h>
using namespace std;

int main(int argc, char *argv[])
{
    vector<char> ss;
    char c = 'a';
    while (c < 'z') {
        ss.push_back(c);
        c++;
    }

    char* p = ss.data();
    fprintf(stderr, "p = %s\n",p);
    return 0;
}

Output:

~/tmp $ g++ test.cpp -o test
~/tmp $ ./test
p = abcdefghijklmnopqrstuvwxy
posted @ 2013-10-30 22:09  英超  Views(546)  Comments(0Edit  收藏  举报