Tuesday Coding Tip 32 — std::span

●5 ●35 ●98
calendar_today ago • schedule1 min read
— Originally published at medium.com

Tuesday coding tips are super short posts about various tidbits mainly from C++, but also from other programming languages I use. You can also follow the #TuesdayCodingTips hashtag on Mastodon and Linkedin.


A common source of mistakes in old C-like code is passing arrays as raw pointers, coupled with a size parameter. Not only is it not compatible with features like ranges or range-based loops of modern C++, but it is also easy to forget about the size parameter and lose it. Or you might forget to free the memory.

std::span is a non-owning wrapper container introduced in C++20 that allows you to store the pointer and the size. That way you can pass along only a single variable, and it gives you adapters for modern iteration and algorithms. If the size of the array is known at compile time, the span can have it as a part of its type (similar to std::array).

#include <span>
#include <iostream>
#include <ranges>

// Function that produces the array pointer
int* functionThatReturnsPointerAndSize(std::size_t& size)
{
    size = 2;
    auto arr = new int[] { 1, 2 };
    return arr;
}

void someLegacyApiCall(int*, std::size_t) {}

int main()
{
    auto size = 0u;
    auto rawPtr = functionThatReturnsPointerAndSize(size);
    auto span = std::span(rawPtr, size);

    // Regular iteration
    for (std::size_t i = 0; i < span.size(); i++) {
        // Sadly, bound-checked at() is a C++26 feature (facepalm)
        // std::cout << span.at(i) << " ";
        std::cout << span[i] << " ";
    }
    std::cout << std::endl;

    // Ranged-based iteration
    for (auto&& item : span) {
        std::cout << item << " ";
    }
    std::cout << std::endl;

    // C++23 ranges are supported
    // filter out even numbers
    for (auto&& item : span | std::views::filter([](int n) { return n % 2 == 1; }))
        std::cout << item << " ";
    std::cout << std::endl;

    // You can read the original pointer and size if you need to
    someLegacyApiCall(span.data(), span.size());

    // Do not forget to free the original pointer
    delete[] span.data();

    return 0;
}

Just keep in mind that since span is non-owning, it won’t clear the memory when it is destroyed. But you can use a smart pointer to do that for you!

#include <span>
#include <iostream>
#include <memory>

// Function that produces the array pointer
int* functionThatReturnsPointerAndSize(std::size_t& size)
{
    size = 2;
    auto arr = new int[size] { 1, 2 };
    return arr;
}

// Custom deleter for the span
// Must delete both internal data and span
// itself as the span is allocated by the smart pointer
void deleteSpan(std::span<int>* span)
{
    delete[] span->data();
    delete span;
    std::cout << "span deleted" << std::endl;
}

int main()
{
    auto size = 0u;
    auto rawPtr = functionThatReturnsPointerAndSize(size);

    auto managedSpan = std::shared_ptr<std::span<int>>(
        new std::span(rawPtr, size), deleteSpan);

    return 0;
}

Want more #cpp & #tuesday-coding-tips deep dives?

Join 6,106+ developers sharing real benchmarks, code breakdowns, and projects. Free forever.

Part 32 of 32 in Tuesday Coding Tips

2 Comments

0 votes
1

More Posts

Tuesday Coding Tip 06 - Explicit template instantiation

Jakub Neruda - Apr 7

Tuesday Coding Tip 02 - Template with type-specific API

Jakub Neruda - Mar 10

Let's play with C++ reflection

Jakub Neruda - Nov 12

Tuesday Coding Tip 31 — Deducing this

Jakub Neruda - Nov 17

Tuesday Coding Tip 17 — Wrapping C APIs

Jakub Neruda - Jun 30
chevron_left
2.2k Points • 138 Badges
Brno, Czech Republic • linkedin.com/in/jakub-neruda
47Posts
40Comments
25Connections
Experienced C++ developer, team lead and hobby gamedev. I enjoy writing stuff about C++, clean code, clean architecture, and game development.

Commenters (This Week)

2 comments
1 comment

Contribute meaningful comments to climb the leaderboard and earn badges!