4

An oft-made claim is that std::valarray was intended to eliminate some forms of aliasing in order to enable better optimization (e.g. see valarray vs. vector: Why was valarray introduced?)

Can anyone elaborate on this claim? It seems to me that aliasing is always possible as long as you can obtain a pointer to an element---which you can, because operator[] returns a reference.

Community
  • 1
  • 1
Brian Bi
  • 111,498
  • 10
  • 176
  • 312
  • 1
    The difference is that if there is aliasing, it is your fault ;-) by using valarray your promised not to do that. – Marc Glisse Oct 20 '14 at 17:27

1 Answers1

2

The "no aliasing" thing refers to the global functions like cos that accept valarray as a parameter. cos (or whatever function) gets applied to the entire array, and the compiler and standard library implementation can assume that the array does not alias and can perform the operation on each element independently.

It also refers to things like valarray's operator+, which does memberwise addition, etc.

Billy ONeal
  • 104,103
  • 58
  • 317
  • 552
  • 1
    "can assume that the array does not alias" - does not alias with what, and why is this the case for `valarray` and not any other kind of array? – Brian Bi Feb 22 '21 at 16:36