The strict aliasing rule dictates that pointers are assumed not to alias if
they point to fundamentally different types. char* and
void* are exceptions. These can alias to any other
data type. The following figure 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. The preceding figure shows the various templates,
including an
intuniverse and afloatuniverse. There is also aMyClassuniverse per design. Additionally there is acharuniverse that includes all universes by default. - Universes do not alias
- Pointer
pcan only point to any address within theintuniverse. Pointerqcan only point to any address within thefloatuniverse. Because of this, pointerpand pointerqcannot be aliased. - Derived pointers point to the original universe
- Pointers derived from a restrict pointer are considered restrict pointers and point to the same restricted memory region. Refer to Derived Pointers.
-
char*universe contains all universes - A
charpointer 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 performance loss.
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