除以大小(void *)是什么意思

what does dividing by sizeof(void *) mean?

本文关键字:是什么 意思 void      更新时间:2023-10-16

我正在使用哈希表,我遇到了这个函数。但是哈希/大小(void *)是什么意思?以及之后给出的评论 - 摆脱已知的 0 位?

// This matches when the hashtable key is a pointer.
      template<class HashKey> class hash_munger<HashKey*> {
       public:
        static size_t MungedHash(size_t hash) {
          // TODO(csilvers): consider rotating instead:
          //    static const int shift = (sizeof(void *) == 4) ? 2 : 3;
          //    return (hash << (sizeof(hash) * 8) - shift)) | (hash >> shift);
          // This matters if we ever change sparse/dense_hash_* to compare
          // hashes before comparing actual values.  It's speedy on x86.
          return hash / sizeof(void*);   // get rid of known-0 bits
        }
      };

在大多数机器和 ABI 上,指针通常是单词对齐的。因此,除以sizeof指针本质上忽略了最小位(例如,在大多数 64 位处理器上,3 个最低位字节地址为 0,因为 64 位字有 8 个字节,每个 8 位)。

看起来它是一个散列指针的函数。指针指向通常对齐的对象。如果此处指向的对象分配了"new",则最有可能与单词边界对齐。

因此,它可能总是能被 8 整除(如果这是单词大小,则为 4)(当转换为数字时),并且该函数将您的数字除以 8 以为您提供指针的真正重要内容。