Skip to content

Instantly share code, notes, and snippets.

@merryhime
Last active March 4, 2016 12:56
Show Gist options
  • Save merryhime/0eff5271ca64ae4a4f29 to your computer and use it in GitHub Desktop.
Save merryhime/0eff5271ca64ae4a4f29 to your computer and use it in GitHub Desktop.
Strict Aliasing

When you construct an object, you allocate memory. For example, T foo; allocates memory sufficient for type T.

In your mental model, associate the block of memory where foo sits with T.

The essense to be safe is:

If a block of memory has type T, you may only use:

  • [const/volatile] T* pointer
  • a [unsigned] char* pointer
  • a U* pointer where U is a union union U { T t; /* ... */ };
  • a P* pointer where P is a type related to T (e.g. base class: struct T : P { /* ... */ })

to refer to it.

There are some other acceptable pointers but the above would cover most cases one would want.


This is why you shouldn't do char buffer[100]; T* t = &buffer; because buffer is char, not T.

This is also why T t; char* u8ptr = &t; is safe.

If a program attempts to access the stored value of an object through a glvalue of other than one of the following types the behavior is undefined:

    the dynamic type of the object,
    a cv-qualified version of the dynamic type of the object,
    a type similar (as defined in 4.4) to the dynamic type of the object,
    a type that is the signed or unsigned type corresponding to the dynamic type of the object,
    a type that is the signed or unsigned type corresponding to a cv-qualified version of the dynamic type of the object,
    an aggregate or union type that includes one of the aforementioned types among its elements or non-static data members (including, recursively, an element or non-static data member of a subaggregate or contained union),
    a type that is a (possibly cv-qualified) base class type of the dynamic type of the object,
    a char or unsigned char type.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment