How std::span changes C++ fundamentally

In C++, we have all sorts of std containers, such as vector. Normally, when we work with vectors, we also pass them around by reference, and vectors of course own their data in a contiguous way.

When a vector is passed to a function, we pass it by reference:

std::vector<int> ints;

auto foo =[&](std::vector<int>& v){
 std::iota( v.begin(), v.end(), 0);
};

foo(ints);

In C++20, there is a new object called: std::span. span is a non-owning object that interfaces like a typical vector. Before standardisation, span was considered a “view”, and that’s what it is.

To start, you can use a span when passing a vector to a function, and perhaps normally should.

std::vector<int> ints(100,0);

auto foo =[&](std::span<int> v){
 std::iota( v.begin(), v.end(), 0);
};

foo(ints);

The span allows us to do really cool stuff with memory management and access, for instance:

std::vector<int> ints(100,0);

std::span<int> a( ints.begin(), 50 )
 , b( ints.begin()+50, ints.end() );

auto foo =[&](std::span<int> v){
 std::iota( v.begin(), v.end(), 0);
};

foo(a);
foo(b);

In this example, a refers to the first half of ints, and b refers to the second half.

We now have two vector like objects that infact refer to a single contiguous segment of memory, cache performance goes up. Spans can be used exactly like vectors, except, they are non-owning and just “views” into owning vectors.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: