Maybe using std::vector with a fixed maximal size?
If boost is allowed then boost::container::static_vector is the closest I can think of.
static_vector is a sequence container like boost::container::vector with contiguous storage that can change in size, along with the static allocation, low overhead, and fixed capacity of boost::array.
The size of each object is still fixed but it can be worth it if the number of allocations is significant and/or the item count is small
boost::container::small_vector is another solution if the vector can grow beyond the limit. The heap is only touched when the size is larger than the defined limit
small_vector is a vector-like container optimized for the case when it contains few elements. It contains some preallocated elements in-place, which can avoid the use of dynamic storage allocation when the actual number of elements is below that preallocated threshold.
boost::container::static_vector<int, 1024> my_array;
boost::container::small_vector<int, 1024> my_vector;
If you use Qt then QVarLengthArray is another way to go:
QVarLengthArray is an attempt to work around this gap in the C++ language. It allocates a certain number of elements on the stack, and if you resize the array to a larger size, it automatically uses the heap instead. Stack allocation has the advantage that it is much faster than heap allocation.
Example:
int myfunc(int n)
{
QVarLengthArray<int, 1024> array(n + 1);
...
return array[n];
}
Some other similar solutions: