Return an array from a function

Question | Sep 27, 2019 | nextptr 

When it comes to working with arrays, the C++11 offers another choice - std::array. An std::array is a struct template that wraps a regular array and provides some convenience methods such as size() and empty(). Let's take an example of where choosing between an std::array and a regular array might make a difference.

A multithreaded application has a struct - StudentRecord - which contains an array of grade points for the five subjects a student has taken in a semester. There is a method - getGradePoints() - that is supposed to return the gradePoints array by value. The array gradePoints need to be returned by value (copy) because another thread can modify it.

class StudentRecord {
 public:
 // ... More members ..

 // auto return type
 // Requires C++14
 auto getGradePoints() {   
    // There might be a lock here   
    return gradePoints;
 }
 private:
  Array_t<double, 5> gradePoints{};
};

Note that, getGradePoints() is returning auto, this feature requires C++14. The gradePoints is declared to be of type Array_t<T, Size>. We have two choices for defining Array_t<T, Size>, one utilizing the std::array and the other that uses a templatized regular array:

A)

template<typename T, size_t Size>
using Array_t = std::array<T,Size>;

B)

template<typename T, size_t Size>
using Array_t = T[Size];

Both of the above implementations compile. However, which one of the above Array_t<T, Size> definitions fulfills our requirement that the getGradePoints() must return a copy of gradePoints?

Select an answer below (check Explanations for details):

2015 nextptr