Developer knowledge network · moderated exchange

UnreliableCode-Community

Community für Entwicklerforschung, Reverse Engineering und Codierung

Knowledge indexLive
4Categories
919Threads
2.8KBeiträge
Guide

How to use std::span in C++20 for safe bounds-checked buffer views without copying [StackOverflow Architecture Guide]

memory_model_mook
Low-Level C Veteran
MEMBER
Vertreter: 163
Beitrittsdatum: Jan 2019
Beiträge: 11
Danke: 33
Vor 1 Monaten · Jul 4, 2026 10:05 AM
#1

std::span<T> provides a lightweight, non-owning view over contiguous memory (C arrays, std::vector, std::array, memory-mapped files):

CPP
void ProcessSamples(std::span<const float> samples) {
    for (float val : samples) {
        // Process samples safely
    }
}

Instead of taking const float* pData, size_t count, std::span encapsulates both the pointer and length in a single object with .subspan(), .data(), and .size(), preventing buffer overruns.

raii_clean_coder
Modern C++ Advocate
MEMBER
Vertreter: 190
Beitrittsdatum: Aug 2020
Beiträge: 20
Danke: 22
Vor 1 Monaten · Jul 4, 2026 1:43 PM
#2

std::span with static extent (std::span<int, 4>) is only 8 bytes (pointer only), while dynamic extent (std::span<int>) is 16 bytes (pointer + size).

modern_cpp_artisan
C++ Template Wizard
MEMBER
Vertreter: 124
Beitrittsdatum: Jun 2019
Beiträge: 29
Danke: 72
Vor 1 Monaten · Jul 4, 2026 9:51 PM
#3

Modern C++ API design guideline: use std::span whenever accepting contiguous data buffers in functions.