長話短說,我有一個指向存盤反轉值的指標,因此當我們計算哈希以驗證資料完整性時,我們需要反轉哈希中使用的資料。然而,散列函式將指標作為輸入。所以我們需要做的是獲取我們的指標,取消參考它以獲取資料,暫時反轉資料,并傳遞對反轉資料的參考。
我已經寫了一些偽代碼來說明我最初是如何做到的。
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;
但是我的代碼審查的同事希望我避免使用臨時變數并將其更改為。
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 變數。如果它甚至可以取消參考指標,請對資料執行運算子,然后將參考傳遞給它而不將值分配給任何東西(因為我相當確定它沒有)。如果有比第一個例子更好的方法來做到這一點。
uj5u.com熱心網友回復:
你需要臨時變數。這個運算式:
hash = Algorithim::Calculate(&~pStartAddress[i], hash);
無效,因為~
運算子的結果不是左值,而&
運算子需要左值。
在旁注中,您可以通過在兩種情況下使用 temp 值來減少代碼中的重復:
uint32_t data = isDiagnostics ? ~pStartAddress[i] : pStartAddress[i];
hash = Algorithim::Calculate(&data, hash);
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/470450.html