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
printf("%f", 233);
  • C++
std::cout << 233;

其中C代码将打印出0,而C++代码则会打印出233。C代码中格式化使用%f是有意为之,结果就是编译器不会报错(除非开启-Werror=format)。如你所见printf不是类型安全的。

再来看看C里面Union在实践中惯用法

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

待续。。。



转载请注明:Serenity » type safe

上一篇

下一篇