Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

`stdstd::string` string is a useful tool for simplifying memory management of strings and avoiding unnecessary copies by reference counting. However there is one common gotcha where it ''causes'' unnecessary copies. Consider:

Code Block
void f(const std::string& s) { cout << s << endl };

void g() {
  for (int i = 0; i <  1000; ++i) { f("hello"); };
}

Wiki Markup
This actually allocates, copies and deletes 1000 heap buffers with the string "hello"! The problem here is that "hello" is ''not'' an instance of `std::string`. It is a
`char5` that must be converted to a temporary `std::string` using the appropriate constructor. However `std::string` always wants to manage its own memory, so the constructor allocates a new buffer and copies the string. Once f() returns and we go round the loop again the temporary is deleted along with its
 char\[5\] that must be converted to a temporary std::string using the appropriate constructor. However std::string always wants to manage its own memory, so the constructor allocates a new buffer and copies the string. Once f() returns and we go round the loop again the temporary is deleted along with its buffer.

Here's a better solution:

...