Fix code constness in CBlockIndex::GetAncestor() overloads

Make the non-const overload of CBlockIndex::GetAncestor() reuse the const overload implementation instead of the other way around. This way, the constness of the const overload implementation is guaranteed. The other way around, it was possible to implement the non-const overload in a way which mutates the object, and since that implementation would be called even for const objects (due to the reuse), we would get undefined behavior.
This commit is contained in:
Dan Raviv 2017-09-15 11:13:25 +03:00
parent 0f399a9ff2
commit b4058ed9c6

View file

@ -80,12 +80,13 @@ int static inline GetSkipHeight(int height) {
return (height & 1) ? InvertLowestOne(InvertLowestOne(height - 1)) + 1 : InvertLowestOne(height); return (height & 1) ? InvertLowestOne(InvertLowestOne(height - 1)) + 1 : InvertLowestOne(height);
} }
CBlockIndex* CBlockIndex::GetAncestor(int height) const CBlockIndex* CBlockIndex::GetAncestor(int height) const
{ {
if (height > nHeight || height < 0) if (height > nHeight || height < 0) {
return nullptr; return nullptr;
}
CBlockIndex* pindexWalk = this; const CBlockIndex* pindexWalk = this;
int heightWalk = nHeight; int heightWalk = nHeight;
while (heightWalk > height) { while (heightWalk > height) {
int heightSkip = GetSkipHeight(heightWalk); int heightSkip = GetSkipHeight(heightWalk);
@ -106,9 +107,9 @@ CBlockIndex* CBlockIndex::GetAncestor(int height)
return pindexWalk; return pindexWalk;
} }
const CBlockIndex* CBlockIndex::GetAncestor(int height) const CBlockIndex* CBlockIndex::GetAncestor(int height)
{ {
return const_cast<CBlockIndex*>(this)->GetAncestor(height); return const_cast<CBlockIndex*>(static_cast<const CBlockIndex*>(this)->GetAncestor(height));
} }
void CBlockIndex::BuildSkip() void CBlockIndex::BuildSkip()