On this page
std::string_view
Prev: std::string | Up: containers | Next: std::unordered_map
Rel: std::string, std::span
Ref: cppreference — std::basic_string_view
Tags: #public #prog #cpp #stdlib #containers #tier/core
Overview
std::string_view (<string_view>, C++17) is a lightweight, non-owning (const char* ptr, std::size_t len) slice over any contiguous character buffer (std::string, string literal, or char[]). Pass it by value for read-only string parameters to avoid heap allocations and copies.
Notes & Pitfalls
- Zero-allocation read-only string slice (pass by value): Avoids copying
std::stringor string literals. - NOT guaranteed NUL-terminated: Never pass
sv.data()to a C function expecting a\0-terminatedconst char*, and never return astring_viewto a localstd::string.
Example
#include <cassert>
#include <string_view>
bool is_comment(std::string_view line) {
return line.starts_with("#") || line.starts_with("//");
}
int main() {
assert(is_comment("// hello") && !is_comment("int x = 1;"));
}
Linked from
Related notes
- tuts/cpp/stdlib/containers/span Linked here; links to this page; shared tags: #containers, #cpp, #prog, #stdlib, #tier
- tuts/cpp/stdlib/containers/string Linked here; links to this page; shared tags: #containers, #cpp, #prog, #stdlib, #tier
- tuts/cpp/stdlib/containers/unordered_map Linked here; links to this page; shared tags: #containers, #cpp, #prog, #stdlib, #tier
- tuts/cpp/stdlib/containers Linked here; links to this page; shared tags: #containers, #cpp, #prog, #stdlib
- tuts/cpp/language_and_raii/raii_smart_pointers_and_lifetime links to this page; shared tags: #cpp, #prog, #tier
- tuts/cpp/stdlib/containers/array shared tags: #containers, #cpp, #prog, #stdlib, #tier
- tuts/cpp/stdlib/containers/expected shared tags: #containers, #cpp, #prog, #stdlib, #tier
- tuts/cpp/stdlib/containers/map shared tags: #containers, #cpp, #prog, #stdlib, #tier
- tuts/cpp/stdlib/containers/optional shared tags: #containers, #cpp, #prog, #stdlib, #tier
- tuts/cpp/stdlib/containers/variant shared tags: #containers, #cpp, #prog, #stdlib, #tier