The strict aliasing rule dictates that pointers are assumed not to alias if
they point to fundamentally different types, except for char*
and void*
which can alias to any
other data type. This is is shown in the following graphic which shows the object
universes and the associated pointers.
Figure 1. Object Universes
- Pointers are associated with a type universe: U(T)
- T is the template and in the preceding graphic the various templates are shown, including an integer universe and a float universe; there is also a MyClass universe per design. Additionally there is a char universe that includes all universes by default.
- Universes do not alias
- Pointer
p
can only point to any address within the integer universe whereas pointerq
can only point to any address within the float universe. Because of this pointer p and pointer q cannot be aliased. - Derived pointers point to the original universe
- Pointers derived from a
restrict
pointer are consideredrestrict
pointers and point to the same restricted memory region. See Derived Pointers. -
char*
universe contains all universes - A
char
pointer can point to any variable in all universes.
For two pointers of the same type, as in the following, where both
p
and q
are int, the compiler is conservative and
aliasing is applied, resulting in loss of performance.
Figure 2. Loss of Performance
For two pointers of different types, as in the following example, where
p
is an int and q
is float, the compiler applies
the strict aliasing rule and an undefined behavior occurs if aliasing exists.
Figure 3. Two Pointers of Different Types