In C++11 we have a new std::array, similar to the boost::array. Example:
std::array<int, 5> fiveInts;
If I would like to use this new arrays in two ways:
- Allocate an array on the stack.
- Allocate an array on the heap.
How to achieve that syntactically? Can that 5 be a variable or only a const?
Template arguments must always be known at compile time. The size of a
std::arraycannot be a variable.The best way to manage a contiguous buffer of values on the heap is via
std::vector, which gives you run-time sizing of the size of the buffer.std::array<int, 5> fiveInts;creates an array of 5 elements on the stack (in automatic storage).std::vector<int> fiveInts(5);creates a managed buffer of 5ints on the heap (in the free store).You could create the full
std::arrayon the heap via callingnew, but I would advise against it.std::arrays main advantage is that it allows stack-based (or internal-to-a-class-based) storage.