Using views
In this section, 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 in this chapter. At the same time, they are closely related to std::string
, std::array
, and std::vector
, which we will look at soon. I 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...