Blender  V3.3
Classes | Namespaces
BLI_span.hh File Reference
#include <algorithm>
#include <array>
#include <iostream>
#include <string>
#include <vector>
#include "BLI_index_range.hh"
#include "BLI_memory_utils.hh"
#include "BLI_utildefines.h"

Go to the source code of this file.

Classes

class  blender::Span< T >
 
class  blender::MutableSpan< T >
 

Namespaces

 blender
 

Detailed Description

An blender::Span<T> references an array that is owned by someone else. It is just a pointer and a size. Since the memory is not owned, Span should not be used to transfer ownership. The array cannot be modified through the Span. However, if T is a non-const pointer, the pointed-to elements can be modified.

There is also blender::MutableSpan<T>. It is mostly the same as Span, but allows the array to be modified.

A (Mutable)Span can refer to data owned by many different data structures including blender::Vector, blender::Array, blender::VectorSet, std::vector, std::array, std::string, std::initializer_list and c-style array.

blender::Span is very similar to std::span (C++20). However, there are a few differences:

blender::Span<T> should be your default choice when you have to pass a read-only array into a function. It is better than passing a const Vector &, because then the function only works for vectors and not for e.g. arrays. Using Span as function parameter makes it usable in more contexts, better expresses the intent and does not sacrifice performance. It is also better than passing a raw pointer and size separately, because it is more convenient and safe.

blender::MutableSpan<T> can be used when a function is supposed to return an array, the size of which is known before the function is called. One advantage of this approach is that the caller is responsible for allocation and deallocation. Furthermore, the function can focus on its task, without having to worry about memory allocation. Alternatively, a function could return an Array or Vector.

NOTE: When a function has a MutableSpan<T> output parameter and T is not a trivial type, then the function has to specify whether the referenced array is expected to be initialized or not.

Since the arrays are only referenced, it is generally unsafe to store a Span. When you store one, you should know who owns the memory.

Instances of Span and MutableSpan are small and should be passed by value.

Definition in file BLI_span.hh.