Eng: Modern C++/arrays

Since there’s a little interest, I’ll be putting together a brief note here and there about new features in C++ and why you might want to use them. Today’s: the new std::array datatype.

C-style arrays have a couple of major things going for them: access to them is blazingly fast (especially when read through sequentially), as usually stack variables are held in chip cache. They also require nothing in the way of memory management, which can be a big win in embedded environments. Against these wins, though, there are some big losses:

  • They’re almost comically susceptible to buffer overflows
  • They’re not particularly well-integrated into the Standard Library

Basically, a pointer into an array can be treated as an iterator for purposes of the Standard Library, but there’s a lot of “meh” involved. A C-style array doesn’t conform to the C++ expectations of standard containers, and all the attempts to pretend otherwise have involved putting a lot of lipstick on a pig.

Welcome to std::array. These are objects in a kinda-sorta sense: conceptually they’re objects templated by type and size, providing a proper C++ container interface to the stack-allocated contents. However, the C++17 standard all but writes in blood “your compiler will reduce these to the exact same Assembly calls it would generate for a C-style array”, meaning this object only exists in your source code: the code optimizer makes all the overhead vanish, leaving you with something that runs with the same performance as C arrays but gives you the much better C++ API for access.

They’re cool. Use them.

One Comment

Leave a Reply