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. string vs string_view
Table
| Aspect | std::string | std::string_view |
|---|---|---|
| Ownership | Owns buffer (typically heap) | Non-owning view |
| Copy cost | Can allocate + copy | Pointer + size copy |
| Mutation | Yes | No |
| Size | Implementation-defined | Usually 16 bytes |
| Null termination | c_str() is NTBS | Not guaranteed by data() alone |
| Lifetime | Managed by string object | Must 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
| Need | Use |
|---|---|
| Read-only text | std::string_view |
| Mutate in place | std::string& |
| Store owned text | std::string member |
| C API needing NTBS | std::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 asstd::stringwhen needed.
Summary
- Read-only parameters: prefer
string_view. - Owned storage:
std::string. - Never let a view outlive the underlying characters.
Related reading
- 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::stringparameters withstring_viewwhere semantics allow. - Use sanitizers to catch use-after-free style mistakes with views.
Related posts
- C++ string (complete)
- C++ any