On this page
  1. std::string_view
  2. Overview
  3. Notes & Pitfalls
  4. Example

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

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