type safe

Type-safe code accesses only the memory locations it is authorized to access. (For this discussion, type safety specifically refers to memory type safety and should not be confused with type safety in a broader respect.) For example, type-safe code cannot read values from another object’s private fields.[1]




C Union

同样,如你所见,union中给ip_str赋值然后使用ip输出,这同样不是类型安全的。这种行为在C++中是undefined behavior (在C中是unspecified)

it’s undefined behavior to read from the member of the union that wasn’t most recently written. Many compilers implement, as a non-standard language extension, the ability to read inactive members of a union.[2]

这时,上面图片中的情况不仅仅是只牵涉到type safe了,还有另外一个东西:strict aliasing。关于strict alias简单来说就是为了优化考虑编译器不允许不同类型的指针指向同一块内存,具体细节可以参考这篇文章(仅供参考)http://blog.qt.io/blog/2011/06/10/type-punning-and-strict-aliasing