C++20 std::span — Modern Array Views Made Simple

C++20 std::span — Modern Array Views Made Simple

C++20 std::span — Modern Array Views Made Simple

In C++20, std::span introduces a powerful concept — a non-owning view over a contiguous array. It gives you the safety of range-based access with the efficiency of pointers.

✅ Basic Example

#include <span>
#include <iostream>

void print(std::span<int> data) {
    for (int x : data) std::cout << x << ' ';
}

int main() {
    int arr[] = {10, 20, 30, 40};
    print(arr); // Implicitly converts to span
}

💡 Why Use std::span?

  • No need to pass raw pointers and sizes separately
  • Works with arrays, vectors, and std::array
  • Doesn't take ownership — safe and lightweight

🛠️ Use Cases in Embedded/Freelance Work

  • Sensor data buffers
  • DMA or audio frame processing
  • Protocol parsing functions

📥 Download the C++20 Cheatsheet

🧠 Cheatsheet by CppStories — shared with credit to the author.

🤝 Need freelance help with C++/embedded projects? Hire me

Comments

Popular posts from this blog

C++17 vs C++20 – Key Feature Differences

Top 5 Modern C++ Features I Use in Real Projects

C++17 Cheatsheet for Embedded Developers