std::string::assign vs std::string::operator=

前端 未结 2 1962
无人共我
无人共我 2020-12-11 15:50

I coded in Borland C++ ages ago, and now I\'m trying to understand the \"new\"(to me) C+11 (I know, we\'re in 2015, there\'s a c+14 ... but I\'m working on an C++11 project)

2条回答
  •  眼角桃花
    2020-12-11 16:21

    Both are equally fast, but = "..." is clearer.

    If you really want fast though, use assign and specify the size:

    test2.assign("Hello again", sizeof("Hello again") - 1); // don't copy the null terminator!
    // or
    test2.assign("Hello again", 11);
    

    That way, only one allocation is needed. (You could also .reserve() enough memory beforehand to get the same effect.)

提交回复
热议问题