我在一些代码中看到了以下注释。
* The implementation uses custom pointer types to save space, and
* to preserve addresses if the underlying container is resized.
* For instance we define `enum class id_t : uint32_t {}`
* instead of (id *)
问题>为什么使用枚举类类型可以保留地址?
答案 0 :(得分:1)
这种技术有时被称为“相对寻址”或“偏移指针”。例如,如果您有一个数组:
int arr[1000];
你想在其中存储两个地点,你可以这样做:
int *x = &arr[40];
int *y = &arr[100];
但你做了:
uint32_t x = 40;
uint32_t y = 100;
然后取消引用其中一个“指针”,你说arr[x]
而不是*x
。
为避免必须保留arr
,您可以封装偏移量:
template <size_t N>
class offsets {
public:
int& operator[](size_t idx) const { return _arr[_off[size_t]]; }
private:
int* _arr;
std::array<uint32_t, N> _off;
}
现在你已经在64位平台上节省了空间,因为你存储了64 + 32 * 4 = 192位,而不是4位常规指针的256位。
如果_arr
发生更改(例如,增大或缩小数组),您也无需更新它们。如果存储的偏移量很大,这可能是一个有意义的优化。