0 day streak
cpp / expert
Snippet

Bounds-Checked Span Implementation for Raw Buffers

This snippet demonstrates an expert implementation of a non-owning array view (similar to std::span). It provides a safe interface for raw buffers by encapsulating the pointer and size, offering both checked and unchecked access patterns for performance optimization.

snippet.cpp
cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
#include <stdexcept>
#include <cstddef>
template <typename T>
class View {
T* ptr;
size_t sz;
public:
constexpr View(T* data, size_t count) : ptr(data), sz(count) {}
constexpr T& at(size_t index) const {
if (index >= sz) throw std::out_of_range("View access out of bounds");
return ptr[index];
}
constexpr T& operator[](size_t index) const noexcept {
return ptr[index]; // Fast access, no check
}
size_t size() const noexcept { return sz; }
};
Breakdown
1
if (index >= sz) throw std::out_of_range(...);
Implements runtime bounds checking to ensure memory safety during buffer access.
2
T& operator[](size_t index) const noexcept
Provides a high-performance, unchecked access operator for use in hot code paths where safety is guaranteed externally.