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

2019-02-22 07:41发布

问题:

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)

Now I have several ways to assign a value to a string.

#include <iostream>
#include <string>
int main ()
{
  std::string test1;
  std::string test2;
  test1 = "Hello World";
  test2.assign("Hello again");

  std::cout << test1 << std::endl << test2;
  return 0;
}

They both work. I learned from http://www.cplusplus.com/reference/string/string/assign/ that there are another ways to use assign . But for simple string assignment, which one is better? I have to fill 100+ structs with 8 std:string each, and I'm looking for the fastest mechanism (I don't care about memory, unless there's a big difference)

回答1:

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.)