Versions Compared

Key

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

The short story: in C++ code using `stdstd::string` string never use string literals except to initialize static-scoped `stdstd::string` string constants.
(And by the way: NeverUseStaticLocalVariables

The long story: `stdstd::string` string is all about avoiding copies. Reference counting and copy-on-write serve to maximise the sharing of a single heap-allocated char array while maintaining memory safety. When used consistently in a program it works rather nicely.

However, when mixed with classic C-style string literals `stdstd::string` string can actually ''cause'' needless heap-allocated copies. Consider these innocent looking constructs:

...

Lines 1-4 all cause creation and destruction of an implicit temporary `stdstd::string` string to hold the literal value. Line 5 does this for every execution of the while loop. That's a new/memcpy/delete each time. The heap is a heavily used resource, in tight inner loops in multi-threaded code this can be a ''severe'' contention bottleneck that cripples scalability.

Use static class `stdstd::string `constants constants or file-private constants instead. You can make global declarations file-private by using a nameless namespace (this is preferred over the use of the `static` static keyword.)

Code Block
namespace { 
   const std::string end("end");
}
void f() { std::string x; while (x != end) {...} }

...