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

问题描述 投票:0回答:1

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

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[]安全?
c++ boost function-pointers declaration
1个回答
2
投票

数组的定义是相关的 - 它是

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

通过指向成员的指向间接使得可以访问点xp坐标作为p.xp[0],并且类似地用于p.yp[1]

否则,有时通过(可能是未定义的)指针技巧或索引上的(可能效率较低)分支来实现。

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

© www.soinside.com 2019 - 2024. All rights reserved.