Using Views
Learn to use std::string_view and std::span to handle sequences of contiguous elements.
We'll cover the following
Overview
In this lesson, we will discuss some relatively new class templates in the C++ standard library: std::string_view
from C++17 and std::span
, which was introduced in C++20.
These class templates are not containers but lightweight views (or slices) of a sequence of contiguous elements. Views are small objects that are meant to be copied by value. They don't allocate memory, nor do they provide any guarantees regarding the lifetime of the memory they point to. In other words, they are non-owning reference types, which differ significantly from the containers described previously. At the same time, they are closely related to std::string
, std::array
, and std::vector
, which we will look at soon. We will start by describing std::string_view
.
Avoiding copies with string_view
A std::string_view
contains a pointer to the beginning of an immutable string buffer and a size. Since a string is a contiguous sequence of characters, the pointer, and the size fully define a valid substring range. Typically, a std::string_view
points to some memory that is owned by a std::string
. But it could also point to a string literal with static storage duration or something like a memory-mapped file. The following diagram shows a std::string_view
pointing at memory owned by a std::string
:
Get hands-on with 1400+ tech skills courses.