std::array are not movable like std::vector, so typically returning it by value would do the copy and if elements are like std::string, the copy can be expensive. If array is small, elements are cheap to copy and code is not required to be that much performant, we can simply return the array.

Another way can be use to out parameter where we pass a reference to array so that the function can fill in the elements in the array.

For example:

void storeItems(std::array<int, 5> &arr_out)
{
    arr_out[0] = 1;
    arr_out[1] = 2;
    arr_out[2] = 3;
    arr_out[3] = 4;
    arr_out[4] = 5;
}
 
std::array<int, 5> items2{};
storeItems(items2);

However, this method has following downsides:

  1. We can’t have function that produces temporary objects.
  2. It is not a conventional way of returning values from the functions.
  3. We can’t use these functions to initialize objects.

References

  1. https://www.learncpp.com/cpp-tutorial/passing-and-returning-stdarray/