Title
Const overload of valarray::operator[] returns by value
Status
cd1
Section
[valarray.access]
Submitter
Gabriel Dos Reis

Created on 2002-11-08.00:00:00 last changed 164 months ago

Messages

Date: 2010-10-21.18:28:33

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.

Date: 2010-10-21.18:28:33

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

Date: 2010-10-21.18:28:33

Proposed resolution:

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

  T operator[](size_t const);

to

  const T& operator[](size_t const);
Date: 2002-11-08.00:00:00

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&.

History
Date User Action Args
2010-10-21 18:28:33adminsetmessages: + msg2453
2010-10-21 18:28:33adminsetmessages: + msg2452
2010-10-21 18:28:33adminsetmessages: + msg2451
2002-11-08 00:00:00admincreate