ReviseAlgo Logo

Arrays and Strings

std::string

C++ string class

Interview: Modern string handling

std::string

std::string is C++'s standard dynamic string class. Unlike C-style char arrays, std::string manages its own memory, tracks length without strlen(), and provides a rich API for manipulation. Most implementations use Short String Optimization (SSO) — storing short strings (typically ≤15 chars) inline in the string object itself, avoiding heap allocation.

Short String Optimization (SSO)

SSO is a performance optimization where the string object itself has a small inline buffer. Strings fitting in this buffer require no heap allocation. This makes creating and copying short strings extremely fast. The threshold is typically 15 bytes (GCC libstdc++) or 22 bytes (MSVC).

std::string_view (C++17)

std::string_view is a lightweight, non-owning reference to a string. It avoids copying when passing read-only string data. Perfect for function parameters that only read a string. Cannot be used for null-terminated C APIs without conversion.

Interview Corner

Q: What is the complexity of std::string concatenation with +=?

A: Amortized O(n) for += (single append), where n is the appended string length. The capacity doubles on reallocation (like vector), so repeated appends are amortized O(1) per character. However, using + in a loop creates temporaries each iteration — O(n²) total. Always use += or std::ostringstream for building strings iteratively.

Common Pitfalls

  • String building with + in loops: Creates O(n²) copies. Use += or reserve + append.
  • std::string_view dangling reference: Storing a string_view to a temporary std::string that is destroyed creates a dangling view.

Best Practices

  • Use std::string_view for read-only string parameters — zero-copy overhead.
  • Use reserve() before bulk appends when the final size is known to avoid reallocations.