Static const std :: vector <char> initialization without heap?
Say I would like to have std :: vector unsigned characters. It is initialized with a list of initializers (this is C ++ 11) and will never change. I would like to avoid heap distribution even during startup and have the entire vector in the data segment, for example, const strings. Is it possible? that is: static const vector<char> v{0x1, 0x2, 0x3, 0x0, 0x5}; (This is a somewhat academic question, I know that it is not so difficult to use C-arrays for this.)
Why not just use 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, which is most likely declared as T arr[N] , where N is the size that you passed in the template (here 5).
While you're here, you might even want to make a constexpr variable, which, as @MSalters points out, gives the compiler even more options to eliminate the repository for v . "
If a fixed size std::array or inline array does not fit, you can define a custom allocator that uses the placement of the new one .
These are many templates to write, so if you can use Boost, boost::container::static_vector is exactly what you are looking for.
OP further asks:
I'm sorry there was no overload for std :: array, which took the size from initializer_list
Your desire is provided by the C ++ 17 output guide:
std::array v {'\x1','\x2','\x3','\x0','\x5'}; static_assert(std::is_same_v<decltype(v), std::array<char,5>>); g++ -std=c++17 since 7.1.0 (Klang doesn't seem to agree with this yet).
cppreference links: Deduction Guide for std :: array , Outputting a Template Template Argument
Note that the initialization list should now have all char values ββin order to infer the type of the array value. Class calculation - all or nothing - you cannot declare an array<char> and have only the size output.