This page is a snapshot from the LWG issues list, see the Library Active Issues List for more information and the meaning of CD1 status.

### 389. Const overload of valarray::operator[] returns by value

Section: 26.7.2.4 [valarray.access] Status: CD1 Submitter: Gabriel Dos Reis Opened: 2002-11-08 Last modified: 2016-01-28

Priority: Not Prioritized

View all other issues in [valarray.access].

View all issues with CD1 status.

Duplicate of: 77

Discussion:

Consider the following program:

        #include <iostream>
        #include <ostream>
        #include <vector>
        #include <valarray>
        #include <algorithm>
        #include <iterator>
        template<typename Array>
        void print(const Array& a)
        {
        using namespace std;
        typedef typename Array::value_type T;
        copy(&a[0], &a[0] + a.size(),
        ostream_iterator<T>(std::cout, " "));
        }
        template<typename T, unsigned N>
        unsigned size(T(&)[N]) { return N; }
        int main()
        {
        double array[] = { 0.89, 9.3, 7, 6.23 };
        std::vector<double> v(array, array + size(array));
        std::valarray<double> w(array, size(array));
        print(v); // #1
        std::cout << std::endl;
        print(w); // #2
        std::cout << std::endl;
        }

While the call numbered #1 succeeds, the call numbered #2 fails because the const version of the member function valarray<T>::operator[](size_t) returns a value instead of a const-reference. That seems to be so for no apparent reason, no benefit. Not only does that defeats users' expectation but it also does hinder existing software (written either in C or Fortran) integration within programs written in C++. There is no reason why subscripting an expression of type valarray<T> that is const-qualified should not return a const T&.

Proposed resolution:

In the class synopsis in 26.7.2 [template.valarray], and in 26.7.2.4 [valarray.access] just above paragraph 1, change

      T operator[](size_t const);

to

      const T& operator[](size_t const);

[Kona: fixed a minor typo: put semicolon at the end of the line wehre it belongs.]

Rationale:

Return by value seems to serve no purpose. Valaray was explicitly designed to have a specified layout so that it could easily be integrated with libraries in other languages, and return by value defeats that purpose. It is believed that this change will have no impact on allowable optimizations.