Developer knowledge network · moderated exchange

Zajednica UnreliableCode

Zajednica za istraživanje, obrnuti inženjering i programiranje programera

Knowledge indexŽivjeti
4Categories
919Threads
2.8KPostovi
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
Rep: 163
Datum pridruživanja: Jan 2019
Postovi: 11
Hvala: 33
prije 1 mjeseci · 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
Rep: 190
Datum pridruživanja: Aug 2020
Postovi: 20
Hvala: 22
prije 1 mjeseci · 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
Rep: 124
Datum pridruživanja: Jun 2019
Postovi: 29
Hvala: 72
prije 1 mjeseci · Jul 4, 2026 9:51 PM
#3

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