variable-length std::array like

dronus picture dronus · Dec 31, 2013 · Viewed 21.9k times · Source

As my usually used C++ compilers allow variable-length arrays (eg. arrays depending on runtime size), I wonder if there is something like std::array with variable size? Of course std::vectoris of variable size, but it allocates on heap, and reallocates on need.

I like to have a stack allocated array with size defined at runtime. Is there any std-template that may feature this? Maybe using std::vector with a fixed maximal size?

Answer

Joseph Mansfield picture Joseph Mansfield · Dec 31, 2013

There are two proposals currently being worked on to bring run-time fixed size arrays to C++ which may be of interest to you:

  • Runtime-sized arrays with automatic storage duration. This would make runtime sized arrays a language feature (like in C11). So you could do:

    void foo(std::size_t size) {
      int arr[size];
    }
    
  • C++ Dynamic Arrays. This would bring a new container to the library, std::dynarray, which is given a fixed size at construction. It is intended to be optimized to be allocated on the stack when possible.

    void foo(std::size_t size) {
      std::dynarray<int> arr(size);
    }
    

These are both being worked on as part of an Array Extensions Technical Specification, which will be released alongside C++14.