Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

static const std::vector<char> initialization without heap?

Tags:

c++

c++11

vector

Let's say I'd like to have a std::vector of unsigned chars. It's initialized with an initializer-list (this is C++11) and will never change. I'd like to avoid any heap allocation, even at startup time, and have the whole vector live in the data segment like const strings. Is that possible? I.e: static const vector<char> v{0x1, 0x2, 0x3, 0x0, 0x5}; (This is a somewhat academic question; I know it's not that hard to just use C arrays for this.)

like image 704
GaryO Avatar asked Jan 31 '18 22:01

GaryO


2 Answers

Why not just use a std::array for this?

static const std::array<char, 5> v{0x1, 0x2, 0x3, 0x0, 0x5};

This avoids any dynamic allocation, since std::array uses an internal array that is most likely declared as T arr[N] where N is the size you passed in the template (Here 5).

While you're here, you might even want to make the variable constexpr, which, as @MSalters points out, "gives the compiler even more opportunity to eliminate the storage for v."

like image 111
Arnav Borborah Avatar answered Oct 01 '22 21:10

Arnav Borborah


If a fixed-size std::array or builtin array isn't suitable, you can define a custom allocator that uses placement new.

That's a lot of boilerplate to write, so if you can use Boost, boost::container::static_vector is exactly what you're looking for.

like image 34
Ray Hamel Avatar answered Oct 01 '22 19:10

Ray Hamel