C++ string vs string_view: Fast, Non-Owning String Handling (C++17)

C++ string vs string_view: Fast, Non-Owning String Handling (C++17)

이 글의 핵심

Practical guide to std::string vs std::string_view: parameters, ownership, dangling risks, and patterns.

Character sequences are a form of resizable array; the same asymptotic picture as arrays and lists often applies to heavy concatenation loops.

Introduction: “My string-heavy code is slow"

"If I pass std::string by value, does it copy?”

std::string_view (C++17) references character data without copying. Using it for read-only parameters removes many allocations/copies.

void print(std::string s);            // may copy
void print(std::string_view s);       // cheap view

This article covers:

  • string vs string_view
  • Benchmarks
  • Parameter guidelines
  • Lifetime pitfalls
  • Patterns

Table of contents

  1. Comparison
  2. Benchmarks
  3. Parameter selection
  4. Pitfalls
  5. Patterns
  6. Summary

1. string vs string_view

Table

Aspectstd::stringstd::string_view
OwnershipOwns buffer (typically heap)Non-owning view
Copy costCan allocate + copyPointer + size copy
MutationYesNo
SizeImplementation-definedUsually 16 bytes
Null terminationc_str() is NTBSNot guaranteed by data() alone
LifetimeManaged by string objectMust outlive the view

2. Benchmarks

Passing std::string by value vs std::string_view vs const std::string& often shows large wins for by-value string parameters in hot loops.

substr: string_view::substr avoids allocating a new string when you only need a view.


3. Parameter selection

NeedUse
Read-only textstd::string_view
Mutate in placestd::string&
Store owned textstd::string member
C API needing NTBSstd::string then c_str()

4. Pitfalls

Dangling views

Do not return a string_view to characters owned by a local std::string that is destroyed.

Not necessarily null-terminated

Do not pass sv.data() to APIs expecting a C string unless you know it is null-terminated or use std::string(sv).c_str().

Temporary string

Binding a string_view to a temporary std::string without extending lifetime is a classic bug.


5. Patterns

  • Parsing/tokenizing with views to avoid substring allocations.
  • Logging APIs taking string_view, storing logs as std::string when needed.

Summary

  • Read-only parameters: prefer string_view.
  • Owned storage: std::string.
  • Never let a view outlive the underlying characters.

  • C++ string_view guide
  • C++ STL string
  • C++ any

Keywords

string vs string_view, C++17, no-copy strings, substring performance

Practical tips

  • Replace by-value std::string parameters with string_view where semantics allow.
  • Use sanitizers to catch use-after-free style mistakes with views.

  • C++ string (complete)
  • C++ any