用于安全 operator[] 访问的指向成员数组的静态指针

Static pointer to member array for safe operator[] access

我正在查看 boost::gil 的源代码,我在二维点 class 中看到了这个注释和相应的代码。

const T& operator[](std::size_t i)          const   { return this->*mem_array[i]; }
      T& operator[](std::size_t i)                  { return this->*mem_array[i]; }

...
private:
// this static array of pointers to member variables makes operator[]
// safe and doesn't seem to exhibit any performance penalty
static T point2<T>::* const mem_array[num_dimensions];

http://www.boost.org/doc/libs/develop/boost/gil/utilities.hpp

问题:

  1. 这到底是做什么的?
  2. 这如何使 operator[] 安全?

数组的定义是相关的——是

template <typename T>
T point2<T>::* const point2<T>::mem_array[point2<T>::num_dimensions] 
    = { &point2<T>::x, &point2<T>::y };

通过指向成员的指针的间接寻址使得访问点 px 坐标成为可能 p.xp[0],并且类似地对于 p.yp[1]

这有时是通过(可能未定义的)指针欺骗或索引上的(可能效率较低的)分支来实现的。

它当然不是绝对安全的,因为没有边界检查,但从符合标准和明确定义的意义上来说它是安全的。