0

In C++, the only way to return an array is by reference:

int ( &unity( int (&arr)[3] ) )[3] {
  arr[0] = 1; arr[1] = arr[2] = 0;
  return arr;
}

Now with C++11, we do have std::array in the STL. It is now possible to return a std::array by copy:

#include <array>
std::array< int, 3 > make_unity() {
  std::array< int, 3 > arr;
  arr[0] = 1; arr[1] = arr[2] = 0;
  return arr;
}

Why is that we are forced to use STL when the compiler could have equivalent functionalities ? Why was it impossible to have a return by copy for arrays in C++11 ?

malat
  • 12,152
  • 13
  • 89
  • 158
  • 1
    It is impossible to return arrays "by copy" because arrays are not copyable. – juanchopanza Dec 10 '14 at 11:28
  • C++ inherited C's notion of arrays that are second class citizens. `std::array` is the first-class citizen version of a compile-time fixed size array, which I recommend using whenever you can. – Joseph Mansfield Dec 10 '14 at 11:35
  • 1
    @juanchopanza arrays are copyable as a struct member or by-value lambda capture. – ecatmur Dec 10 '14 at 11:38
  • my question was closed as duplicate, however the explanation there was not clear at all and entered just in the detail of stack allocation. I prefered the explanation `arrays are not l-values so receiving it in the calling function would have to use a new variable with initialisation`, see: http://stackoverflow.com/a/5157483/136285 – malat Dec 10 '14 at 11:52

1 Answers1

0

It's not that std::array can be passed via value; it's that it is a class that wraps complex behaviours.

When you pass an std::array by value, what is happening is that some code is run which allocates the correct space for the new array and copies all the values. It's not part of the language, somebody had to implement the actual thing.

Also, std::array and a C array are NOT the same thing, so do not confuse them!

Svalorzen
  • 5,353
  • 3
  • 30
  • 54