bhylu.com

Advertisements

C++ std::span and std::string_view

Pass size-aware views without copying and keep their owners alive and unchanged.

How it works

std::span provides a pointer-and-length view of contiguous elements. std::string_view provides a non-owning view of character data. Neither view keeps its owner alive, and string_view does not promise a terminator at its logical end. These types make range information explicit at a call, but they do not repair dangling storage or check every subscript. A view should normally be used for the duration of a call unless the API states a longer borrowing lifetime.

Run it locally

Use a C++20 compiler and matching standard library in a separate lab folder. The command uses c++; substitute g++, clang++ or zig c++ for your toolchain. C++ does not currently run in Bhylu’s browser playground. Apache, PHP and MySQL are not needed.

c++ -std=c++20 -Wall -Wextra -Wpedantic -Werror views.cpp -o lesson

On Windows use -o lesson.exe and run .\lesson.exe in PowerShell. On Unix-like systems run ./lesson. Thread examples may need -pthread on your platform.

Download the complete C++ source. Run file labs in a private empty directory, away from existing reports.

Example

C++20 · views.cpp

#include <iostream>
#include <span>
#include <array>
#include <string_view>

int total(std::span<const int> values) {
    int result{0};
    for (int value : values) { result += value; }
    return result;
}

int main() {
    std::array<int, 3> parcels{3, 4, 5};
    std::cout << "Total: " << total(parcels) << '\n';
    std::string_view stop{"North gate"};
    std::cout << "Zone: " << stop.substr(0, 5) << '\n';
}

Expected result

Total: 12
Zone: North

The array owns all three ints while total borrows their range. The small fixture’s sum fits int; the view does not enforce arithmetic safety. The text view borrows a static literal, so its substring remains live. A view into a vector may dangle after growth, and a string view into a temporary string can dangle immediately after the creating statement.

Consult the WG21 C++ working group and the C++ Core Guidelines for language references and design guidance. Check the selected standard version and your implementation’s library support.