0 day streak
cpp / intermediate
Snippet

Non-Owning Buffer Views for Contiguous Memory

A std::span is a non-owning object that refers to a contiguous sequence of objects. It provides a uniform interface to access data stored in arrays, vectors, or other contiguous containers without copying, improving performance and API flexibility.

snippet.cpp
cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
#include <span>
#include <vector>
#include <iostream>
void update_buffer(std::span<int> view) {
for (int& val : view) {
val *= 2;
}
}
int main() {
int raw_arr[] = {1, 2, 3};
std::vector<int> vec = {4, 5, 6};
update_buffer(raw_arr); // Works with C-style arrays
update_buffer(vec); // Works with std::vector
}
Breakdown
1
void update_buffer(std::span<int> view)
Defines a function that accepts any contiguous block of integers.
2
for (int& val : view)
Iterates over the elements pointed to by the span.