I want to initialize an array of doubles in a separate function and pass the result back to the caller. At compile time I do not know the exact size, I just know it is small (1-100). I assume that the most efficient way is to allocate the memory on stack at the caller site and pass it to the function. Can I do this in a functional programming style as well without much performance overhead? For instance, returning a std::vector<double>
instance would require a heap allocation. Alternatively, one could return an instance of boost::container::small_vector
, which would avoid the heap allocation, but requires using boost. Is there any other way to do this?
int main() {
auto size = calculateSize();
// version 1: most efficient I guess
// double data[size];
double* data = (double*)alloca(sizeof(double) * size);
initData(data, size);
// version 2 - what type should data2 have to minimize overhead with respect to first version?
auto data2 = initData(size);
}
Update Adjusted stack memory allocation to make it standard conform c++.
This question is not about variable length arrays but about good alternatives to avoid heap allocation when returning small arrays from functions.