Hands-On High Performance Programming with Qt 5
上QQ阅读APP看书,第一时间看更新

Aliasing

Let's assume we wrote the following simple function:

void addThroughPointers(int* ptr1, int* ptr2, int* ptrValue)
{
*ptr1 += *ptrValue;
*ptr2 += *ptrValue;
}

What could be difficult here? Well, in C and C++ there is no guarantee that all three pointers do not point to the same place in memory and hence that changing one pointer won't affect the other pointers. So, the compiler cannot use cached values but it has to reread the pointed-to values every time.

The C99 standard introduced the restrict modifier for the pointers exactly for this reason and it hints to the compiler that the pointers do not alias each other, allowing it to skip the rereading of values to assure consistency. Unfortunately, C++ still doesn't support it, and the best that we can do is to use compiler-specific extensions, that is, __restrict in GCC and __restrict__ in Microsoft compiler. In the case of the MinGW compiler, we are using the following:

void addThroughPointers2(int* __restrict ptr1, int* __restrict ptr2, 
int* __restrict ptrValue)

An interesting fact is that the memcpy function is defined in the C99 standard with restricted source and destination pointers, hence making its behavior in cases of overlapping pointers undefined. C++ doesn't have the restrict qualifier, but it defines the same undefined behavior, hence implicitly treating those pointers as restricted!