代码之家  ›  专栏  ›  技术社区  ›  Falderol

建议在指针处临时反转数据,然后将指针传递给临时反转的数据

  •  1
  • Falderol  · 技术社区  · 3 年前

    长话短说,我有一个指针指向一个存储为倒排的值,所以当我们计算散列来验证数据的完整性时,我们需要倒排散列中使用的数据。然而,哈希函数将指针作为输入。所以我们需要做的是取下指针,解引用它来获取数据,暂时反转数据,然后传递一个对反转数据的引用。

    我已经写了一些我最初是如何做的伪代码。

    uint32_t hash = 0;
    MemoryBlock pMemoryBlock = pAllocator->GetFirstMemoryBlock();
    while(nullptr != pMemoryBlock)
    {
        uint32_t size = pMemoryBlock->getWordsUsed();
        const uint32_t* pStartAddress = pMemoryBlock->GetStartAddress();
        for (uint32_t i = 0; i < size; i++)
        {
            if (isDiagnostics)
            {
                uint32_t inverted_data = ~(pStartAddress[i]);
                hash = Algorithim::Calculate(&inverted_data, hash);
            }
            else
            {
                hash = Algorithim::Calculate(&pStartAddress[i], hash);
            }
        }
        pMemoryBlock->GetNextMemoryBlock();
    }
    return hash;
    

    但是我的一位同事在我的代码审查中希望我避免使用temp变量,并将其更改为。

    uint32_t hash = 0;
    MemoryBlock pMemoryBlock = pAllocator->GetFirstMemoryBlock();
    while(nullptr != pMemoryBlock)
    {
        uint32_t size = pMemoryBlock->getWordsUsed();
        const uint32_t* pStartAddress = pMemoryBlock->GetStartAddress();
        for (uint32_t i = 0; i < size; i++)
        {
            if (isDiagnostics)
            {
                hash = Algorithim::Calculate(&~pStartAddress[i], hash);
            }
            else
            {
                hash = Algorithim::Calculate(&pStartAddress[i], hash);
            }
        }
        pMemoryBlock->GetNextMemoryBlock();
    }
    return hash;
    

    我想知道是否有真正的理由避免使用temp变量。如果它甚至可以解引用一个指针,对数据执行一个操作符,然后传递一个对它的引用,而不给任何东西赋值(因为我很确定它不会)。如果有比第一个例子更好的方法。

    1 回复  |  直到 3 年前
        1
  •  3
  •   dbush    3 年前

    你需要临时变量。这句话:

    hash = Algorithim::Calculate(&~pStartAddress[i], hash);
    

    无效,因为 ~ 运算符不是左值 & 运算符需要左值。

    另一方面,您可以通过在两种情况下使用temp值来减少代码中的重复:

        uint32_t data = isDiagnostics ? ~pStartAddress[i] : pStartAddress[i];
        hash = Algorithim::Calculate(&data, hash);