c++assignment-operatorproxy-classesvalarray

Why do some assignment operators for the helper classes of std::valarray return void?


For example, the assignment operators for std::slice_array:

void operator=(const valarray<T>&) const; //#1
void operator=(const T&) const; //#2
const slice_array& operator=(const slice_array&) const; //#3

#1 and #2 return void, but #3 returns const slice_array&.

It prohibits some code, such as:

std::valarray<int> va{1, 2, 3, 4, 5, 6};
va[std::slice(3, 2, 2)] = va[std::slice(0, 2, 2)] = va[0];

Why?


Solution

  • While returning a reference from operator= is the common and reasonable way for implementations, keep in mind that valarray is a rarely used and an unsupported library. See C++ valarray vs. vector for more detailed answers on this topic.

    From one of the answers:

    ISTR that the main reason it wasn't removed from the standard is that nobody took the time to evaluate the issue thoroughly and write a proposal to remove it.

    Even before going into debates about opinions, there are bugs in the current implementation. See assigning to gslice_array gives runtime error for instance.