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.)
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
."
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With