std::string::assign 对比 std::string::operator=

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

我很久以前用 Borland C++ 编写代码,现在我正在尝试理解 "new"(对我来说)C+11(我知道,我们在 2015 年,有一个 c+14 。 .. 但我正在做一个 C++11 项目)

现在我有几种方法可以给字符串赋值。

#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;
}

它们都有效。我从 http://www.cplusplus.com/reference/string/string/assign/ 了解到还有另一种使用方式 assign 。但是对于简单的字符串赋值,哪个更好呢?我必须用 8 个 std:string 填充 100 多个结构,我正在寻找最快的机制(我不关心内存,除非有很大的不同)

两者同样快,但= "..."更清晰。

如果您真的想要快,请使用 assign 并指定大小:

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

这样,只需要一次分配。 (你也可以预先 .reserve() 足够的内存来获得相同的效果。)

我尝试了两种方式的基准测试。

static void string_assign_method(benchmark::State& state) {
  std::string str;
  std::string base="123456789";  
  // Code inside this loop is measured repeatedly
  for (auto _ : state) {
    str.assign(base, 9);
  }
}
// Register the function as a benchmark
BENCHMARK(string_assign_method);

static void string_assign_operator(benchmark::State& state) {
  std::string str;
  std::string base="123456789";   
  // Code before the loop is not measured
  for (auto _ : state) {
    str = base;
  }
}
BENCHMARK(string_assign_operator);

Here为图形化对比解。似乎这两种方法都同样快。赋值运算符有更好的结果。

仅当必须分配基本字符串中的特定位置时才使用 string::assign。