1

I'm trying to construct a 2D vector class myself.

When I'm looking for sample code implemented by others, I found this:

class Vector2D {
 public:

  // components
  double x, y;

  Vector2D() : x( 0.0 ), y( 0.0 ) { }

  // returns reference to the specified component (0-based indexing: x, y)
  inline double& operator[] ( const int& index ) {
    return ( &x )[ index ];
  }
}

How is the [] operator overloaded? How do I understand (&x)[index]?

Lightness Races in Orbit
  • 378,754
  • 76
  • 643
  • 1,055
jinglei
  • 3,269
  • 11
  • 27
  • 46
  • 9
    You found garbage. Change your learning material to something that [makes sense](https://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list/388282). – nwp May 03 '17 at 13:51
  • 3
    I believe this example is undefined behavior. It relies on `y` being immediately after `x` in memory and I'm not certain that this is guaranteed. – François Andrieux May 03 '17 at 13:51
  • 3
    `const int& index` is premature pessimism. It adds a layer of indirection with no possible gain. – François Andrieux May 03 '17 at 13:53

1 Answers1

5

How is the [] operator overloaded?

Badly.

How do I understand (&x)[index]?

It's a line of code that pretends we can safely navigate around a class's members using pointer arithmetic. We can't. The code is broken.

Furthermore, taking an int by const reference is just stupid; there's essentially no way that's going to be of use to an optimiser. ints are tiny, possibly even smaller than the pointer that your compiler is likely to need "under the hood" to implement this reference.

Lightness Races in Orbit
  • 378,754
  • 76
  • 643
  • 1,055
  • I wouldn't be so sure that it's broken; `Vector2D` as it is is standard layout (actually, it's even POD), and the standard gives much stronger guarantees about the layout in memory for standard layout classes. – Matteo Italia May 03 '17 at 14:11
  • 1
    @MatteoItalia: You simply can't use pointer arithmetic to "jump" objects like this, no matter what their layout is. C++14 5.7/5 is clear that this is UB. – Lightness Races in Orbit May 03 '17 at 14:12
  • @BoundaryImposition that reference to the standard is important enough to be part of the answer. – Mark Ransom May 04 '17 at 01:21