Is `=` a sequence point – or how do you guard against aliasing via reference parameters?

  aliasing, c++, pass-by-reference, sequence-points

Coming from a long (~20ys) abstinence in C++, it seems I’m having problems with trivialities. Given the code:

template<typename T, std::size_t DIM>
void add(std::array<T, DIM> &tgt, std::array<T, DIM> a, std::array<T, DIM> b)
{
  for (int i = 0; i < DIM; i++) {
    tgt[i] = a[i] + b[i];
  }
}

which should do a vector addition obviously, I see a big problem when any of the sources a or b is identical to tgt in the call. I seem to remember that = does not constitute a sequence point so the operation is UB. What is the best practice to write such code – or to evade writing such code?

PS: feel free to comment on any other atrocities I inflicted upon good taste and such

Source: Windows Questions C++

LEAVE A COMMENT