0Pricing
C++ Academy · Lesson

Why string_view

Avoid string copies.

The Cost of Copies

Passing std::string by value copies the whole buffer. For read-only access that copy is wasted work. std::string_view is a lightweight, non-owning view, just a pointer and a length. Include <string_view>.

#include <iostream>
#include <string_view>
int main() {
    std::string_view sv = "hello";
    std::cout << sv << " len=" << sv.size() << "\n";
}

What a View Holds

A string_view stores only a pointer to existing characters and a length. It does not own or copy the data.

#include <iostream>
#include <string>
#include <string_view>
int main() {
    std::string s = "world";
    std::string_view sv = s; // views s, no copy
    std::cout << sv << "\n";
}

All lessons in this course

  1. Why string_view
  2. Creating Views
  3. Pitfalls and Lifetimes
  4. String Algorithms
← Back to C++ Academy